【问题标题】:Replacing "tokens" in Python string with alternate values用备用值替换 Python 字符串中的“令牌”
【发布时间】:2014-10-29 08:50:46
【问题描述】:

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

http://whatever.org/?title=@Title@&note=@Note@

...以及令牌列表:

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

将这些标记插入到字符串中的最 Pythonic 方式是什么,这样,使用上面的示例,会生成以下内容:

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

我考虑过:

  1. 循环遍历列表,对于其中包含的每个字符串,拆分出令牌名称,并对找到的每个@TOKEN_NAME 实例进行正则表达式替换;和

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

【问题讨论】:

    标签: python python-2.7 interpolation


    【解决方案1】:

    要使用 Pythonic 解决方案,请采用 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/?title=@Title@&note=@Note@"
    >>> 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'}
    

    【讨论】:

    • 简单明了;谢谢。你能解释一下** 在你的第二个例子中在字典前面做了什么吗?
    • 太棒了。非常感谢。
    • 我已经运行了上面的,re.sub 语句不起作用
    • @MarkKortink 有没有比“不起作用”更多的机会?
    • 当我设置s = "http://whatever.org/?title=@Title@&note=@Note@" 然后运行re.sub(r"@(\w+?)@", r"{\1}", s) 我得到s 不变。是否有无需使用format() 即可解决初始问题的正则表达式?原因,我正在使用 jinja,它使用 {{ }} 括起来变量,所以给定格式使用 { } 有可能出现错误。
    猜你喜欢
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2021-05-16
    • 2023-04-11
    • 1970-01-01
    • 2020-11-12
    相关资源
    最近更新 更多