1. 程式人生 > >Python3.4-文字-替換字串中的子串

Python3.4-文字-替換字串中的子串

"""
python版本: 3.4
替換字串中的子串
"""
import string

info = """姓名: $name,
年齡: $age,
部落格: $blog,
http://${weibo},
$$帥
"""
#string.Template(template)
info_template = string.Template(info)

#以字典的方式一一賦值
info_dic={'name':'畢小朋','age':30,'blog':'http://blog.csdn.net/wirelessqa','weibo':"www.weibo.com/wirelessqa"}

#substitute(mapping, **kwds)
print(info_template.substitute(info_dic))
"""
>>
姓名: 畢小朋,
年齡: 30,
部落格: http://blog.csdn.net/wirelessqa,
http://www.weibo.com,
$帥
"""

#轉成字典後再賦值
info_dic2=dict(name='畢小朋',age=30,blog='http://blog.csdn.net/wirelessqa',weibo='www.weibo.com/wirelessqa')

print(info_template.substitute(info_dic2))
"""
>>
姓名: 畢小朋,
年齡: 30,
部落格: http://blog.csdn.net/wirelessqa,
http://www.weibo.com,
$帥
"""

#safe_substitute(mapping, **kwds)
#當我們少一個鍵(weibo被拿掉了哦)時,檢視結果如何
test_safe_substitute=dict(name='畢小朋',age=30,blog='http://blog.csdn.net/wirelessqa')

try:
	print(info_template.substitute(test_safe_substitute))
except KeyError:
	print("error: 對映中沒有weibo這個鍵")

"""
>>
error: 對映中沒有weibo這個鍵
"""
#使用safe_substitute(mapping, **kwds)
print(info_template.safe_substitute(test_safe_substitute))
"""
>>
姓名: 畢小朋,
年齡: 30,
部落格: http://blog.csdn.net/wirelessqa,
http://${weibo},
$帥
"""

#locals()提供了基於字典的訪問區域性變數的方式
info = string.Template('老畢是$shuai,芳齡$age')
shuai='帥哥'
age=18
print(info.substitute(locals())) #>>老畢是帥哥,芳齡18

#使用關鍵字作為引數替換
info = string.Template('老畢喜歡年齡$age的$who')
for i in range(18,39):
	print(info.substitute(age=i,who='美女'))

"""
>>
老畢喜歡年齡18的美女
老畢喜歡年齡19的美女
老畢喜歡年齡20的美女
老畢喜歡年齡21的美女
....
老畢喜歡年齡38的美女
"""

#同時使用關鍵字引數和字典
for age in range(18,39):
	print(info.substitute(locals(),who='美女'))
"""
>>
老畢喜歡年齡18的美女
老畢喜歡年齡19的美女
老畢喜歡年齡20的美女
老畢喜歡年齡21的美女
....
老畢喜歡年齡38的美女
"""