【问题标题】:Is there a way to use the String replace() Method to replace anything有没有办法使用 String replace() 方法来替换任何东西
【发布时间】:2016-08-23 13:59:23
【问题描述】:

有点像

sentence.replace(*, "newword")

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

我们说

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

应该返回“newword newword”

【问题讨论】:

  • sentence.replace(*, "newword") 会返回什么?
  • 假设sentence = "hello world",那么它应该返回sentence = "newword newword"
  • 试试sentence = ' '.join(['newword'] * len(sentence.split()))

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


【解决方案1】:

由于您不会替换特定的单词,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 并在下面演示:

【讨论】:

  • 愚蠢的手指。谢谢,我已经相应地调整了。
【解决方案2】:

您正在寻找的是单词替换。因此,您需要的不是替换字符的 string.replace,而是替换所有单词的东西。

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

在上面的例子中,我们将句子插入到它的单词列表中,然后简单地制作另一个相同长度的单词“newword”列表。最后,我们将新词与它们之间的“ ”字符连接在一起

【讨论】:

    【解决方案3】:

    如果您关心速度,手动制作字符串似乎快两倍:

    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 测试中,所以我没有包含它)

    【讨论】:

    • 谢谢你,杰耶姆!
    猜你喜欢
    • 2019-10-15
    • 1970-01-01
    • 2013-04-29
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多