Python标准库--string模块
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 !"#$%&‘()*+,-./:;<=>[email protected][\]^_`{|}~ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&‘()*+,-./:;<=>[email protected][\]^_`{|}~ """ # 第一个是几个空行,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
以上是关于Python标准库--string模块的主要内容,如果未能解决你的问题,请参考以下文章