我有一个在后端代码中被替换的字符串。${}表示要替换的字符串模式。例子 -
${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。
qq_笑_17
慕神8447489
一只名叫tom的猫
相关分类