【问题标题】:How do I search a string for multiple strings, and then replace them with other strings? (Python) [duplicate]如何在一个字符串中搜索多个字符串,然后用其他字符串替换它们? (Python)[重复]
【发布时间】:2017-05-02 08:06:31
【问题描述】:

我有以下句子“那个人去了商店”,我想用“狗”替换任何有“th”或“sh”的单词。结果应该是这样的:

dogse man 去 dogse dogsop

这是我的代码到目前为止的样子:

sentence = "the man went to the shop"

to_be_replaced = ["th", "sh"]
replaced_with = "dogs"

for terms in to_be_replaced:
    if terms in sentence:
        new_sentence = sentence.replace(terms,replaced_with)
        print new_sentence

目前,这打印:

dogse man went to dogse shop
the man went to the dogsop

我希望它只打印这个:

dogse man went to dogse dogsop

我会这样做吗?

【问题讨论】:

  • 不是最好的实现,但如果你重新绑定到sentence,它会起作用;将new_sentence 更改为sentence

标签: python string replace


【解决方案1】:

这应该可行:

s.replace("th", "dogs").replace("sh", "dogs")

【讨论】:

    【解决方案2】:

    您只需从一开始就处理相同的字符串并继续处理它。您不需要 new_sentence(除非您想保留第一个)。

    这段代码应该可以工作:

    sentence = "the man went to the shop"
    
    to_be_replaced = ["th", "sh"]
    replaced_with = "dogs"
    
    for terms in to_be_replaced:
        if terms in sentence:
            sentence = sentence.replace(terms,replaced_with)
    print sentence
    

    应该打印出来:

    dogse man went to dogse dogsop
    

    【讨论】:

      【解决方案3】:
      import re
      
      text = "the man went to the shop"
      repalceed = re.sub(r'sh|th', 'dogs', text)
      print(repalceed)
      

      出来:

      dogse man went to dogse dogsop
      

      【讨论】:

        猜你喜欢
        • 2013-03-14
        • 2020-04-01
        • 1970-01-01
        • 2020-01-06
        • 2021-12-24
        • 1970-01-01
        • 2012-07-08
        相关资源
        最近更新 更多