猿问

使用 format 函数替换 python 字符串

我有一个在后端代码中被替换的字符串。${}表示要替换的字符串模式。例子 -


${location}我要去${days}


我有一个字典,其中的值要在下面替换。我想查找${location}文本中是否存在并将其替换为 中的键值str_replacements。下面是我的代码。使用 时字符串替换不起作用.format。它可以使用%s,但我不想使用它。


text = "I am going to ${location} for ${days}"

str_replacements = {

    'location': 'earth',

    'days': 100,

    'vehicle': 'car',

}


for key, val in str_replacements.iteritems():

    str_to_replace = '${{}}'.format(key)

    # str_to_replace returned is ${}. I want the key to be present here.

    # For instance the value of str_to_replace needs to be ${location} so

    # that i can replace it in the text

        text = text.replace(str_to_replace, val)

我不想用%s字符串来替换。我想用功能来实现功能.format。


Pythonpython-2.7

我有一个在后端代码中被替换的字符串。${}表示要替换的字符串模式。例子 -


${location}我要去${days}


我有一个字典,其中的值要在下面替换。我想查找${location}文本中是否存在并将其替换为 中的键值str_replacements。下面是我的代码。使用 时字符串替换不起作用.format。它可以使用%s,但我不想使用它。


text = "I am going to ${location} for ${days}"

str_replacements = {

    'location': 'earth',

    'days': 100,

    'vehicle': 'car',

}


for key, val in str_replacements.iteritems():

    str_to_replace = '${{}}'.format(key)

    # str_to_replace returned is ${}. I want the key to be present here.

    # For instance the value of str_to_replace needs to be ${location} so

    # that i can replace it in the text

    if str_to_replace in text:

        text = text.replace(str_to_replace, val)

我不想用%s字符串来替换。我想用功能来实现功能.format。

心有法竹
浏览 137回答 3
3回答

qq_笑_17

使用额外的{}前任:text = "I am going to ${location} for ${days}"str_replacements = {    'location': 'earth',    'days': 100,    'vehicle': 'car',}for key, val in str_replacements.items():    str_to_replace = '${{{}}}'.format(key)    if str_to_replace in text:        text = text.replace(str_to_replace, str(val))print(text)#  -> I am going to earth for 100

慕神8447489

您可以使用一个小的正则表达式来代替:import retext = "I am going to ${location} for ${days} ${leave_me_alone}"str_replacements = {    'location': 'earth',    'days': 100,    'vehicle': 'car',}rx = re.compile(r'\$\{([^{}]+)\}')text = rx.sub(lambda m: str(str_replacements.get(m.group(1), m.group(0))), text)print(text)这会产生I am going to earth for 100 ${leave_me_alone}

一只名叫tom的猫

您可以通过两种方式完成此操作:参数化 - 不严格遵循参数的顺序非参数化 - 未严格遵循参数顺序示例如下:
随时随地看视频慕课网APP

相关分类

Python
我要回答