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

标签 python string python-2.7 python-3.x methods

有点像

sentence.replace(*, "newword")

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

假设

sentence = " Hello World " return sentence.replace(*, "新世界")

应该返回“新词新词”

最佳答案

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

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

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

示例

你可以找到一个complete interactive example of this here并在下面演示:

enter image description here

关于python - 有没有办法使用 String replace() 方法来替换任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920854/

相关文章:

python Selenium : How to let human interaction in a automated script?

python - pywt `_ctw` 模块上的 Pyinstaller ImportError

c# - 如何使用 C# 对 IP 地址列表进行排序

c# - 使用 spring.net 创建字符串对象

python - 按位运算 : C vs. Python

python - 了解 Python 导入和循环依赖的行为

python - 替换字符串中的货币值时,Python 中的 re.sub() 并不总是有效

javascript - 如何在 React 应用程序中使用 Fetch 向 Flask API 发送 POST 请求

c++ - char数组声明中字符串文字周围的大括号有效吗? (例如 char s[] = {"Hello World"})

python - Django Web 应用程序的棘手编码逻辑