您好,欢迎访问一九零五行业门户网

Python模块之string.py介绍

这篇文章讲述python模块之string.py介绍用法字符串常量:
import string
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 !#$%&'()*+,-./:;96b4fef55684b9312718d5de63fb7121?@[\]^_`{|}~ 0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz!#$%&'()*+,-     ./:;96b4fef55684b9312718d5de63fb7121?@[\]^_`{|}~
1.template类:
其实,template类,可以和格式化字符串的用法还有字符串对象的format()方法做对比,可以帮助更好地理解。首先,新建一个python文件:string_template.py,
然后在里面写入以下内容:
import string values = {'var': 'foo'} t = string.template( variable        : $var escape          : $$ variable in text: ${var}iable ) print('template:', t.substitute(values)) s =  variable        : %(var)s escape          : %% variable in text: %(var)siable print('interpolation:', s % values) s =  variable        : {var} escape          : {{}} variable in text: {var}iable print('format:', s.format(**values))
然后,在python命令行中输入:
$ python string_template.py
结果
template: variable        : foo escape          : $ variable in text: fooiable interpolation: variable        : foo escape          : % variable in text: fooiable format: variable        : foo escape          : {}
可以看到三者之间都可以起到对字符串里进行格式化的效果。只是三者的修饰符不一样。template类好的一点就是其可以通过继承类,实例化后自定义其修饰符,并且也可以对变量的名字格式进行正则表达式的定义。如string_template_advanced.py示例:
import string
class mytemplate(string.template): delimiter = '%' idpattern = '[a-z]+_[a-z]+' template_text = ''' delimiter : %% replaced : %with_underscore igonred : %notunderscored ''' d = { 'with_underscore': 'replaced', 'notunderscored': 'not replaced', } t = mytemplate(template_text) print('modified id pattern:') print(t.safe_substitute(d))
首先,解释下上面python文件。里面定义了一个类mytemplate,继承了string的template类,然后,对其两个域进行重载: delimiter为修饰符,现在指定为了‘%’,而不是之前的‘$’。 接着,idpattern是对变量的格式指定。
结果
$ python string_template_advanced.py modified id pattern: delimiter : % replaced : replaced igonred : %notunderscored
为什么notunderscored没有被替换呢?原因是我们在类定义的时候,idpattern里指定要出现下划线'_', 而该变量名并没有下划线,故替代不了。
以上就是python模块之string.py介绍的详细内容。
其它类似信息

推荐信息