Replacing specific words in a string (Python)

2020-01-27 06:34发布

I would like to replace words in a string sentence such as:

What $noun$ is $verb$?

What's the regular expression to replace the characters in '$ $' (inclusive) with actual nouns/verbs?

3条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-27 07:11

You don't need a regular expression for that. I would do

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

Only use regular expressions when needed. It's generally slower.

查看更多
相关推荐>>
3楼-- · 2020-01-27 07:25
In [1]: import re

In [2]: re.sub('\$noun\$', 'the heck', 'What $noun$ is $verb$?')
Out[2]: 'What the heck is $verb$?'
查看更多
你好瞎i
4楼-- · 2020-01-27 07:30

Given that you are free to modify $noun$ etc. to your liking, best practise to do this nowadays is probably to using the format function on a string:

"What {noun} is {verb}?".format(noun="XXX", verb="YYY")
查看更多
登录 后发表回答