有没有办法使用String replace()方法来替换任何东西

anq*_*ros 1 python string methods python-2.7 python-3.x

就像是

sentence.replace(*, "newword")

(这不起作用,顺便说一句)

让我们说吧

sentence = "hello world" return sentence.replace(*, "newworld")

应该返回"newword newword"

Rio*_*ams 5

由于您不打算替换特定单词,str.replace()因此不会真正支持任何类型的模式匹配.

但是,您可以使用re.sub()允许您传入一个匹配所有内容并替换它的正则表达式的函数:

import re
# Replace each series of non-space characters [^\s]+ with "newword"
sentence = re.sub('[^\s]+','newword',sentence)
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到完整的交互式示例,并在下面演示:

在此输入图像描述