Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python单词替换(用dict中的值替换大括号中的值)_Python_Regex_Substitution - Fatal编程技术网

Python单词替换(用dict中的值替换大括号中的值)

Python单词替换(用dict中的值替换大括号中的值),python,regex,substitution,Python,Regex,Substitution,我对正则表达式的理解很糟糕,我需要帮助做一些替换。我搜索过类似的问题,但它们都与我的问题有点太大的不同 基本上,我有一个可用参数的dict,如下所示: available_params = {'item1': 'dog', 'item2': 'cat', 'item3': 'horse'} 我收到这样一个字符串: str = 'The {item3} and the {item2} kicked the {item1}.' 我只想用相应的dict值替换大括号值,得到以下结果: 马和猫踢了狗

我对正则表达式的理解很糟糕,我需要帮助做一些替换。我搜索过类似的问题,但它们都与我的问题有点太大的不同

基本上,我有一个可用参数的dict,如下所示:

available_params = {'item1': 'dog', 'item2': 'cat', 'item3': 'horse'}
我收到这样一个字符串:

str = 'The {item3} and the {item2} kicked the {item1}.'
我只想用相应的dict值替换大括号值,得到以下结果:

马和猫踢了狗

看起来这应该很容易,但我不确定最好的方法是什么


任何帮助都将不胜感激。

您可以使用
**
dict
作为参数传递给
str format
。有一件事,请不要使用
str
作为变量名

>>>str.format(**available_params)
'The horse and the cat kicked the dog.'

您可以使用
**
dict
作为参数传递给
str格式
。有一件事,请不要使用
str
作为变量名

>>>str.format(**available_params)
'The horse and the cat kicked the dog.'

使用dict将其传递到
str.format
并避免使用
str
作为变量名

s = 'The {item3} and the {item2} kicked the {item1}.' 

s.format(**available_params)

每个占位符名称必须与dict中的一个键匹配,否则会出现错误。

使用dict将其传递到
str.format
并避免使用
str
作为变量名称

s = 'The {item3} and the {item2} kicked the {item1}.' 

s.format(**available_params)

每个占位符名称都必须与dict中的一个键匹配,否则会出现错误。

喜欢这个地方,感谢您的快速回答。我觉得应该很简单。不过,我还有一个问题,如果收到的值不在dict中,会不会导致异常?是的。
***
用于解包
dict
爱这个地方,感谢您的快速回答。我觉得应该很简单。不过我还有一个问题,如果收到的值不在dict中,会不会导致异常?是。
**
用于解包
dict
谢谢。并且不会使用str作为我的变量名,只是用作示例。谢谢。不会使用str作为变量名,只是用作示例。