Displaying posts tagged with

“locals”

Python食谱-1.17.Python2.4中解析替换字符串中的变量

原文作者:John Nielsen, Lawrence Oluyede, Nick Coghlan 中文编译:Tony (digitalsatori) 问题 使用Python2.4,我们如何才能用简单的方法做到将字符串中特殊标记的标示符用字典中标示符所对应的值来替代呢? 解决方法 Python2.4中的 string.Template 可以用来处理此类问题,以下说明如何使用该类: import string # 创建字符串模板用 $ 符号标记标示符 new_style = string.Template('this is $thing') # 使用 template 的 substitute 方法,用一个匹配字典作为其参数 print new_style.substitute({'thing':5}) # 输出: this is 5 print new_style.substitute({'thing':'test'}) # 输出: this is test # 你也可以用键-值对来处理替换对象 print new_style.substitute(thing=5) # 输出: this is 5 print [...]