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
    
    
  • 相关阅读:
    flume配置和说明(转)
    ganlia安装配置文档
    (转)传统MySQL+ Memcached架构遇到的问题
    (转)QRCODE二维码介绍及常用控件推荐
    (转) VS2012程序打包部署详解
    (转)安装程序发布利器——InstallShield 2011 Limited Edition
    (转)linux下mysql的安装过程
    (转)反向代理服务器的工作原理
    (转)工业4.0消灭淘宝只需十年
    (转)TCP注册端口号大全
  • 原文地址:https://www.cnblogs.com/hailongchen/p/10871110.html
Copyright © 2011-2022 走看看