生成指定的字符串
import string
print(string.ascii_letters) #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_lowercase) #abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase) #ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits) #0123456789
print(string.hexdigits) #0123456789abcdefABCDEF
print(string.octdigits) #01234567
字符串的置换
string模块的一个非常有用的功能是字符串的置换
。
字符串的置换1
import string
values = {'name': 'whw', 'age': 28, 'sex': 'male'}
# 1、string.Template(s1).substitute(values)方法
s1 = '''
Name :$name
Age :$age
Sex :$sex
Text :${name} is a1 good boy
'''
ret1 = string.Template(s1)
print('一:string.Template(s1).substitute(values)方法:', ret1.substitute(values))
# 2、%操作符实现
s2 = '''
Name:%(name)s
Age:%(age)s
Sex:%(sex)s
Text:%(name)s is a1 GOOD BOY
'''
ret2 = s2 % (values)
print('二:%操作符方法', ret2)
# 3、format格式化
s3 = '''
Name::{name}
Age::{age}
Sex::{sex}
Text::{name} IS A GOOD BOY
'''
ret3 = s3.format(**values)
print('三:format方法:', ret3)
字符串的置换2——safe_substitute方法
import string
values = {'var': 'foo'}
s = '$var is here but $missing is not here'
try:
print(string.Template(s).substitute(values))
except KeyError as err:
print('ERROR:', str(err))
print('safe_substitute()方法:\n', string.Template(s).safe_substitute(values))