繁体   English   中英

替换字符串中的特定单词 (Python)

[英]Replacing specific words in a string (Python)

我想替换字符串句子中的单词,例如:

What $noun$ is $verb$?

用实际名词/动词替换'$ $'(含)中的字符的正则表达式是什么?

你不需要正则表达式。 我会做

str = "What $noun$ is $verb$?"
print str.replace("$noun$", "the heck")

仅在需要时使用正则表达式。 它通常较慢。

鉴于您可以根据自己的喜好自由修改$noun$等,现在最好的做法是在字符串上使用format函数:

"What {noun} is {verb}?".format(noun="XXX", verb="YYY")
In [1]: import re

In [2]: re.sub('\$noun\$', 'the heck', 'What $noun$ is $verb$?')
Out[2]: 'What the heck is $verb$?'

使用字典来保存正则表达式模式和值。 使用 re.sub 替换令牌。

dict = {
   "(\$noun\$)" : "ABC",
   "(\$verb\$)": "DEF"
} 
new_str=str
for key,value in dict.items():
   new_str=(re.sub(key, value, new_str))
print(new_str)

输出:

What ABC is DEF?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM