string模块

# string Moudle

"""
Data:
    ascii_letters          大小写字母 
    ascii_lowercase        小写字母
    ascii_uppercase        大写字母
    digits                 数字0-9
    hexdigits              十六进制 0123456789abcdefABCDEF
    octdigits              八进制数 01234567  
    printable              全ascii字符
    punctuation            标点符号
    whitespace             '\t\n\r\x0b\x0c'
"""

 

# string方法
imoport string
s
= 'learn python' print(string.capwords(s)) # 转为标题,单词首字母大写

 

import string
d = {'a':'var'}

s ="""
V:${a}
E:$$
T:${a}able
"""

t = string.Template(s)  # $为其语法结构
print(t.substitute(d))
# Templates类的2个方法区别
import string

d = {'a':'key'}
s = '$a is here but $missing is not provided'

t = string.Template(s)

try:
    print('substitute() :', t.substitute(d))
except KeyError as err:
    print('ERROR:', str(err))

print('safe_substitute():', t.safe_substitute(d))
# 进阶
import string

class MyTemplate(string.Template):
    delimiter = '%'  # 语法$修改为语法%
    idpattern = '[a-z]+_[a-z]+'  # 该形式的正则,进行语法,否则忽略


d = {
    'with_underscore': 'replaced',
    'notunderscored': 'not replaced'
}

s = """
D:%%
R:%with_underscore
I:%notunderscored
"""

t = MyTemplate(s)
print(t.safe_substitute(d))

 

posted @ 2019-01-30 13:06  怒放吧!  阅读(103)  评论(0编辑  收藏  举报
我的