Displaying posts tagged with

“string.Template”

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 [...]

Python食谱-1.16.替换字符串中的变量

原文作者:Scott David Daniels 中文编译:Tony (digitalsatori) 问题 如何才能用简单的方法将字符串中的一些特殊标记的子串替换为一个字典中定义的字符串。 解决方法 以下的解决方法对Python2.3以上的版本有效: def expand(format, d, marker='"', safe=False): if safe: def lookup(w): return d.get(w, w.join(marker*2)) else: def lookup(w): return d[w] parts = format.split(marker) parts[1::2] = map(lookup, parts[1::2]) return ''.join(parts) if _ _name_ _ == '_ _main_ _': print expand('just "a" test', {'a': 'one'}) # emits: just one test 当参数 [...]