zoukankan      html  css  js  c++  java
  • Python标准库--string模块

    string中包含了处理文本的常量和模板

    常量

    print(string.whitespace)
    print(string.ascii_lowercase)
    print(string.ascii_uppercase)
    print(string.ascii_letters)
    print(string.digits)
    print(string.hexdigits)
    print(string.octdigits)
    print(string.punctuation)
    print(string.printable)
    
    """
         
    
    abcdefghijklmnopqrstuvwxyz
    ABCDEFGHIJKLMNOPQRSTUVWXYZ
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
    0123456789
    0123456789abcdefABCDEF
    01234567
    !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
    0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[]^_`{|}~     
    
    
    """
    # 第一个是几个空行,Windows输出有点问题

    函数

    capwords():每个单词首字母大写,可自定义单词间分隔符
    s = 'This is a dog'
    print(s)
    print(string.capwords(s))
    
    s2 = 'This-is-a-dog'
    print(s2)
    print(string.capwords(s2, '-'))
    
    """
    This is a dog
    This Is A Dog
    This-is-a-dog
    This-Is-A-Dog
    
    """

    模板

    substitute() 传入模板变量, 没有就报错
    safe_substitute() 捕获异常,原样输出
     
    values = {'var': 'boo'}
    
    t = string.Template("""
        Variable        :$var
        Excape          : $$
        Variable in text: ${var}iable
    """)
    
    print(t.substitute(values))
    
    t2 = string.Template("$var is here but $missing is not provided")
    
    try:
        print(t2.substitute(values))
    except KeyError as err:
        print('ERROR:', str(err))
    
    print(t2.safe_substitute(values))
    
    """
    
        Variable        :boo
        Excape          : $
        Variable in text: booiable
    
    ERROR: 'missing'
    boo is here but $missing is not provided
    """

    $$ 输出 $

    自定义模板类继承string中的模板类,可自定义变量定界符,和变量查找规则

    class MyTemplate(string.Template):
        delimiter = '%'
        idpattern = '[a-z]+_[a-z]+'

    Formatter

  • 相关阅读:
    微信小程序上拉分页
    关于检测数据类型,三种方法(typeof,instanceof,Object.prototype.toString.call())优缺点
    如何在Devc++中配置OpenCv
    数据库系统和应用
    这是一篇测试文档
    Pandas 表格合并
    es6一些好用的方法总结
    前端面试题
    超有趣! JS是怎么计算1+2!!!
    彻底理解闭包
  • 原文地址:https://www.cnblogs.com/wj5633/p/6931028.html
Copyright © 2011-2022 走看看