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

2024-09-28 17:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

像这样的

sentence.replace(*, "newword")

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

比如说

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

应该返回“newword newword”


Tags: helloworldreturnsentencereplacenewwordnewworld
3条回答

因为您不打算替换特定的单词,^{}实际上不支持任何类型的模式匹配。你知道吗

但是,您可以使用^{}函数,该函数允许您传入一个与所有内容匹配的正则表达式并替换它:

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

你要找的是一个替换词。所以字符串.替换如果要替换字符,则需要替换所有单词的内容。你知道吗

>>> sentence = "hello world this is my sentence"
>>> " ".join(["newword"] * len(sentence.split()))
'newword newword newword newword newword newword'

在上面的例子中,我们将这个句子放入一个单词列表中,然后简单地列出另一个相同长度的单词“newword”。最后,我们把生词和它们之间的“”字符连接起来

如果你关心速度,仅仅手工制作字符串似乎要快一倍:

In [8]: import re

In [9]: sentence = "hello world this is my sentence"

In [10]: nonspace = re.compile('[^\s]+')

In [11]: %timeit re.sub(nonspace, 'newword', sentence)
100000 loops, best of 3: 6.28 µs per loop

In [12]: %timeit ' '.join('newword' for _ in xrange(len(sentence.split())))
100000 loops, best of 3: 2.52 µs per loop

In [13]: sentence *= 40  # Make the sentence longer

In [14]: %timeit re.sub(nonspace, 'newword', sentence)
10000 loops, best of 3: 70.6 µs per loop

In [15]: %timeit ' '.join('newword' for _ in xrange(len(sentence.split())))
10000 loops, best of 3: 30.2 µs per loop

而且join实际上是faster when you hand it a list,因此' '.join(['newword' for _ in xrange(len(sentence.split()))])应该会带来一些性能改进(它将结果缓存在非正式的%timeit测试中,所以我没有包含它)

相关问题 更多 >