使用格式函数替换 python 字符串
Replace a python string using format function
我有一个在后端代码中被替换的字符串。 ${}
表示要替换字符串模式。例子-
I am going to ${location}
for ${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
函数实现功能。
使用额外的{}
例如:
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
您可以改用一个小的正则表达式:
import re
text = "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}
您可以通过两种方式完成:
- 参数化 - 参数顺序未严格遵守
- 非参数化 - 参数顺序未严格遵守
例子如下:
我有一个在后端代码中被替换的字符串。 ${}
表示要替换字符串模式。例子-
I am going to
${location}
for${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
函数实现功能。
使用额外的{}
例如:
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
您可以改用一个小的正则表达式:
import re
text = "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}
您可以通过两种方式完成:
- 参数化 - 参数顺序未严格遵守
- 非参数化 - 参数顺序未严格遵守
例子如下: