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

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 !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz!"#$%&'()*+,- ./:;<=>?@[\]^_`{|}~
二、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的详细内容。
其它类似信息

推荐信息