【问题标题】:Replace a string with corresponding value from a list of strings用字符串列表中的相应值替换字符串
【发布时间】:2021-08-02 18:27:21
【问题描述】:

我有一个字符串列表和一些文本字符串如下:

my_list = ['en','di','fi','ope']

test_strings = ['you cannot enter', 'the wound is open', 'the house is clean']

如果 test_strings 中的最后一个单词出现在列表中,我想用上面列表中的相应字符串替换它们。我编写了一个 for 循环来捕获模式,但不知道如何进行替换(?)。

for entry in [entry for entry in test_strings]:
    if entry.split(' ', 1)[-1].startswith(tuple(my_list)):
          output = entry.replace(entry,?)

作为我想要的输出:

 output = ['you cannot en', 'the wound is ope', 'the house is clean']

【问题讨论】:

  • 请编辑您的问题并显示此输入的示例输出
  • 感谢您指出这一点。我添加了一个示例输出

标签: python string list replace


【解决方案1】:
for i,v in enumerate(test_strings):
    last_term = v.split(' ')[-1]
    for k in my_list:
        if last_term.startswith(k):
            test_strings[i] = v.replace(last_term,k)
            break
print(test_strings)  

['you cannot en', 'the wound is ope', 'the house is clean']

【讨论】:

    【解决方案2】:
    my_list = ['en', 'di', 'fi', 'ope']
    
    test_strings = ['you cannot enter', 'the wound is open', 'the house is clean']
    
    for i in range(len(test_strings)):
        temp = test_strings[i].split(" ")
        last_word = temp[-1]
        for j in my_list:
            if last_word.startswith(j):
                break
        else:
            j = last_word
        temp[-1] = j
        test_strings[i] = " ".join(temp)
    

    在此之后,test_strings 将是必需的。 为了替换文本,列表的index 已重新分配给新文本。

    【讨论】:

      猜你喜欢
      • 2013-05-01
      • 2021-05-22
      • 2019-06-06
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2022-06-14
      相关资源
      最近更新 更多