【问题标题】:Match all the list elements with a string and removing the string parts if matched将所有列表元素与字符串匹配,如果匹配则删除字符串部分
【发布时间】:2021-01-30 08:17:49
【问题描述】:
import re    
my_list=['apple', 'oranges' , 'peaches']
string= ' \apples\ \cherries\ \bananas\ \peaches\ \avocado\ \oranges\ '
for x in my_list:
    replace=re.sub(x,' ',string)
    print(replace)

正确的输出:- ' \cherries\ \bananas\ \avocado\ '

这段代码哪里出错了?

【问题讨论】:

  • 为什么x 在引号中:'x'
  • 我不明白。 'x' 仅表示其中包含值 x 的字符串。例如,这并不意味着apple
  • 哦,我明白了,我错了,我现在编辑了它,但仍在 for 循环中,循环为列表中的每个元素迭代它。有解决办法吗?

标签: python python-3.x string list python-re


【解决方案1】:
import re

a = ['apples', 'oranges' , 'peaches']
input_text = ' \\apples\\ \\cherries\\ \\bananas\\ \\peaches\\ \\avocado\\ \\oranges\\ '

output_text = re.sub(r'({})'.format('|'.join(['\\\\{}\\\\'.format(x) for x in a])), '', input_text)

output_text 是:

  \cherries\ \bananas\  \avocado\  

【讨论】:

    【解决方案2】:

    您可以使用.replace(),它可能更容易:

    my_list=['apples', 'oranges' , 'peaches'] # note typo in original post
    string= r' \apples\ \cherries\ \bananas\ \peaches\ \avocado\ \oranges\ '
    
    for item in my_list:
        thestring = '\\' + item + '\\ '
        string = string.replace(thestring, '')
    print(string)
    

    输出:

     \cherries\ \bananas\ \avocado\
    

    但是,如果在最后一个反斜杠之后有可变数量的空格,则最好使用正则表达式并在搜索词末尾使用 ' ?'

    在任何一种情况下,print() 语句都应该在循环之外。

    【讨论】:

      猜你喜欢
      • 2021-11-12
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 2013-06-04
      • 2014-01-09
      • 2021-04-17
      • 1970-01-01
      • 2020-05-02
      相关资源
      最近更新 更多