簡體   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