Python Cookbook学习记录 ch1_17_2013/10/25
1.16替换字符串中的字串
给定一个字符串,通过查询一个替换字典,将字典中被标记的子字符串替换掉
>>> new_style = string.Template('this is $fst and this is $snd') >>> print new_style.substitute(fst=5,snd=10) this is 5 and this is 10 >>> print new_style.substitute({'fst':5,'snd':10}) this is 5 and this is 10
文中还举了一个例子,其中两个$可以代表$:
>>> form_letter = '''Dear $customer, I hope you are having a great time. If you do not find Room $room to your satisfaction, let us know. Please accept this $$5 coupon. Sincerely, $manager ${name}Inn''' >>> letter_template = string.Template(form_letter) >>> print letter_template.substitute({'name':'Sleepy', 'customer':'Fred Smith', 'manager':'Barney Mills', 'room':307, }) Dear Fred Smith, I hope you are having a great time. If you do not find Room 307 to your satisfaction, let us know. Please accept this $5 coupon. Sincerely, Barney Mills SleepyInn
浙公网安备 33010602011771号