2014-09-04 75 views
2

的问题在Python字符串具有替代值替换 “令牌”

想象接收的字符串的脚本:

http://whatever.org/[email protected]@&[email protected]@

...和令牌的列表:

['arg:Title=SampleTitle', 'arg:Note=SampleNote']

什么是插入这些令牌的最Pythonic方式S插入的字符串,例如,当使用上述例子中,产生下列操作:

http://whatever.org/?title=SampleTitle&note=SampleNote

我的思想

  1. 遍历该列表,并且对于它包含每个字符串,拆分出令牌名称,并在发现的每个实例@TOKEN_NAME上执行正则表达式替换。

  2. 使用某种模板机制(类似于Ruby的ERB.template)。

帮助?

我对Python相当陌生,很喜欢专家的看法。谢谢!

回答

8

要使用Python化解决方案,采用str.format规格为format string syntax

>>> template = "http://whatever.org/?title={Title}&note={Note}" 
>>> template.format(Title="SampleTitle", Note="SampleNote") 
'http://whatever.org/?title=SampleTitle&note=SampleNote' 

您也可以解压的命名参数的字典:

>>> template.format(**{"Title": "SampleTitle", "Note": "SampleNote"}) 
'http://whatever.org/?title=SampleTitle&note=SampleNote' 

如果你坚持你的输入格式,你可以很容易地切换到更有用的东西regular expression

>>> import re 
>>> s = "http://whatever.org/[email protected]@&[email protected]@" 
>>> re.sub(r"@(\w+?)@", r"{\1}", s) 
'http://whatever.org/?title={Title}&note={Note}' 

(见正则表达式的解释here

和令牌处理成一个词典,也:

>>> tokens = ['arg:Title=SampleTitle', 'arg:Note=SampleNote'] 
>>> dict(s[4:].split("=") for s in tokens) 
{'Note': 'SampleNote', 'Title': 'SampleTitle'} 
+0

简单和直接的;谢谢。你能解释第二个例子中字典前面的'**'做什么吗? – ABach 2014-09-04 14:59:04

+0

@ABach参见例如http://stackoverflow.com/q/36901/3001761 – jonrsharpe 2014-09-04 14:59:39

+0

太棒了。非常感谢。 – ABach 2014-09-04 15:03:11