网络编程
位置:首页>> 网络编程>> Python编程>> Python中模块string.py详解

Python中模块string.py详解

作者:Brad1994  发布时间:2021-05-20 05:25:03 

标签: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里指定要出现下划线'_', 而该变量名并没有下划线,故替代不了。

总结

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com