在一个串置换特定字(Python)的(Replacing specific words in a s

2019-06-18 06:25发布

我想在一个字符串的语句,如更换的话:

What $noun$ is $verb$?

什么是正则表达式与实际的名词/动词替换“$ $”(含)的角色?

Answer 1:

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

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

仅在需要时使用正则表达式。 这是一般较慢。



Answer 2:

既然你可以自由地修改$noun$等,根据自己的喜好,最好的做法要做到这一点现在可能是使用format的字符串函数:

"What {noun} is {verb}?".format(noun="XXX", verb="YYY")


Answer 3:

In [1]: import re

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


文章来源: Replacing specific words in a string (Python)