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
    
    
  • 相关阅读:
    控制容器的反转和依赖注入模式
    缓存和内存区别
    数据库知识总结:sqlserver中事务总结:begin tran,rollback tran,commit tran +IndexDB总结
    SqlServer数据库1433端口问题1
    网络配置:IP+NETMASK+GATEWAY+DNS
    Shell脚本中非交互式修改密码的方法(转)
    Linux之sed:删除某行以及替换
    每日命令:(3)pwd
    Linux目录结构详细介绍
    关于Linux字符集的查看及修改
  • 原文地址:https://www.cnblogs.com/hailongchen/p/10871110.html
Copyright © 2011-2022 走看看