为了账号安全,请及时绑定邮箱和手机立即绑定

使用 format 函数替换 python 字符串

使用 format 函数替换 python 字符串

心有法竹 2023-10-11 21:38:12
我有一个在后端代码中被替换的字符串。${}表示要替换的字符串模式。例子 -${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。
查看完整描述

3 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

使用额外的{}


前任:


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


查看完整回答
反对 回复 2023-10-11
?
慕神8447489

TA贡献1780条经验 获得超1个赞

您可以使用一个小的正则表达式来代替:


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}


查看完整回答
反对 回复 2023-10-11
?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

您可以通过两种方式完成此操作:

  1. 参数化 - 不严格遵循参数的顺序

  2. 非参数化 - 未严格遵循参数顺序

示例如下:

https://img1.sycdn.imooc.com/6526a59000019a4b03890188.jpg

查看完整回答
反对 回复 2023-10-11
  • 3 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信