zoukankan      html  css  js  c++  java
  • [每日一讲] Python系列:字符串(下)

    字符串的常见操作

    """
    DATA STRUCTURE
    Container: Sequence
    —— String
    String is immutable.If string transfer to List, it can be mutable.
    Another way to change the content of Strings, use inner API, such as replace(),
    translate(), find(), join(), split().

    数据结构
    容器:序列
    —— 字符串
    字符串是不可变的。如果将之转换成列表,则可变。
    另一种改变字符串的方式,使用字符串方法,诸如 replace(), translate(), find(), join(), split().

    """


    字符串方法

    def string_api():
    
        words = "这是一段文字,包括了一些符合对如()[],也有一些特殊符号!@#$"
    
        print(words.title())    # 打印结果为:这是一段文字,包括了一些符合对如()[],也有一些特殊符号!@#$
        print('/'.join(words))    # 打印结果为:这/是/一/段/文/字/,/包/括/了/一/些/符/合/对/如/(/)/[/]/,/也/有/一/些/特/殊/符/号/!/@/#/$
        print(words.split(',', 2))   # 打印结果为:['这是一段文字', '包括了一些符合对如()[],也有一些特殊符号!@#$']
        print(words.replace("是", "展示出了"))    # 打印结果为:这展示出了一段文字,包括了一些符合对如()[],也有一些特殊符号!@#$
        print(words.find('!'))    # 打印结果为:29
        print(words[:5])    #打印结果为:这是一段文
    
    

    格式化字符串方式

    详细可见 https://docs.python.org/zh-cn/3.7/tutorial/introduction.html#strings

    #! /usr/bin/python
    # coding:utf-8
    
    from math import pi
    
    
    class StringFormat:
    
        @staticmethod
        def string_format():
            string = 'Hey, %s. %s enough for ya?'
            values = ('guys', 'Hot')
            # This is simple-format
            # 简单字符串格式化方法
            print(string % values)
            # This is standard format
            # 标准字符串格式化方法
            string_d = 'Hello, {1}. {0} enough for ya?'.format("Hot", "guys")
            print(string_d)
            # This is for remaining 2 decimals
            # 保留2位数
            print("{name} is approximately {value:.2f}.".format(value=pi, name="π"))
            # transfer symbol
            # 转换标识符
            print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
    
        @staticmethod
        def string_sub(string='Hello'):
            if string.find('o') != -1:
                print('find one character:o')
                print('the first index of substring is:' + str(string.find('o')) + " position")
            else:
                print("nothing")
    
    
    if __name__ == '__main__':
        StringFormat.string_format()
        StringFormat.string_sub()
    
    

    字符串模板方式

    #! /usr/bin/python
    # coding:utf-8
    
    
    from string import Template
    
    
    def tmplt_action():
        s1 = Template('$who like $what')
        print(s1.substitute(who='tim', what='eat'))
    
    
    tmplt_action()    # 输出结果为:tim like eat
    
    
  • 相关阅读:
    OpenGL ES学习001---绘制三角形
    Mac关机时处于黑屏状态
    静态变量和实例变量的区别(配图解释专业术语,通俗易懂)
    用shape画内圆外方,形成一个圆形头像
    最全的敏捷认证对比(CSM/PMI-ACP/EXIN)
    Certified Scrum Master CSM 中文资料大全
    如何打造优秀的远程敏捷团队(9步)
    博客搬家
    权威的国际敏捷认证Certified Scrum Master (CSM)
    博客园入驻了
  • 原文地址:https://www.cnblogs.com/hailongchen/p/10871110.html
Copyright © 2011-2022 走看看