【问题标题】:Replace every instance of a word with another word without breaking other words containing that word用另一个词替换一个词的每个实例,而不会破坏包含该词的其他词
【发布时间】:2020-03-16 15:51:06
【问题描述】:

单词,单词,单词...对不起标题。

假设我想将字符串中的每个“yes”实例替换为“no”。我可以使用 string.replace()。但是接下来就出现了这个问题:

string = "yes eyes yesterday yes"
new_str = string.replace("yes", "no")

# new_str -> "no eno noterday no"

如何通过将“是”更改为“否”来保持“眼睛”和“昨天”的原样。

【问题讨论】:

标签: python python-3.x string replace


【解决方案1】:

您可以在此处使用re

re.sub(r'\byes\b','no',"yes eyes yesterday yes")
# 'no eyes yesterday no'

来自docs

\b- 匹配空字符串,但只匹配单词的开头或结尾。单词被定义为单词字符的序列。请注意,正式地,\b 定义为\w\W 字符之间的边界(反之亦然),或\w 和字符串的开头/结尾之间的边界。这意味着r'\bfoo\b' 匹配'foo''foo.''(foo)''bar foo baz',但不匹配'foobar' or 'foo3'

【讨论】:

    【解决方案2】:
    " ".join(["no" if word=="yes" else word for word in string.split()])
    
    'no eyes yesterday no'
    

    解释:

    首先,将字符串分解为单个单词的列表:

    string.split()
    
    ['yes', 'eyes', 'yesterday', 'yes']
    

    然后遍历这个单个单词的列表并使用表达式

    "no" if word=="yes" else word
    

    "no" 替换列表理解中的每个"yes"

    ["no" if word=="yes" else word for word in string.split()]
    
    ['no', 'eyes', 'yesterday', 'no']
    

    最后,使用字符串" "(分隔符)的.join() 方法将这个更改后的列表返回到一个字符串。

    【讨论】:

      【解决方案3】:

      试试这个:

      import re
      
      string = "yes eyes yesterday yes"
      new_str = re.sub(r"\byes\b", "no", string)
      

      输出:

      no eyes yesterday no
      

      【讨论】:

        【解决方案4】:

        如果你使用正则表达式,你可以用\b指定单词边界:

        import re
        
        sentence = 'yes no yesyes'
        
        sentence = re.sub(r'\byes\b', 'no', sentence)
        print(sentence)
        

        输出:

        no no yesyes
        

        请注意,“yesyes”没有更改(变为“no”)。

        您可以阅读有关 Python 的 re 模块 here 的更多信息。

        【讨论】:

          猜你喜欢
          • 2021-10-02
          • 2019-09-24
          • 2012-02-26
          • 1970-01-01
          • 2023-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多