替换字符串中的特定单词 (Python) [英] Replacing specific words in a string (Python)

查看:78
本文介绍了替换字符串中的特定单词 (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您不需要正则表达式.我愿意

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.

这篇关于替换字符串中的特定单词 (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆