无法弄清如何使用re.sub并在列表上迭代

2024-04-29 17:22:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望它遍历这个列表,检查列表中的每一项是否都在var txt中,如果它们在那里,就用空格替换它们。如你所见,我只能得到列表中第一个要替换的项目。如何让它迭代列表中的每一项?谢谢。你知道吗

import re

txt='affirmed and the affirmance and AFFIRMED and Affirm case'

wordList = ['case', 'affirm\w+', '(ca\w+)']
for word in wordList:
    out = re.sub(wordList[0], '', txt, re.I)
    #out = re.sub(r'\Abaffirm.+', '', txt, re.IGNORECASE)

print txt
print out

输出:

affirmed and the affirmance and AFFIRMED and Affirm case
affirmed and the affirmance and AFFIRMED and Affirm 

Tags: andtheretxt列表varoutcase
1条回答
网友
1楼 · 发布于 2024-04-29 17:22:20

这里有几点需要注意:

  1. 有一个for循环,每次迭代都访问第一个条目(wordList[0]),而不是当前条目(word)。你知道吗
  2. 每次迭代都会覆盖输出,因此只会删除wordList中的最后一个条目。你知道吗

所以,工作循环可能是这样的:

wordList = ['case', 'affirm\w+', '(ca\w+)']
out = txt
for word in wordList:
    out = re.sub(word, '', out, re.I)

print txt
print out

在你的建议之后,我把它编辑得更进一步,缩短到这个。你知道吗

import re
txt='affirmed and the affirmance and AFFIRMED and Affirm case'
wordList = ['affirm\w+', '(ca\w+)']
for word in wordList:
    txt = re.sub(word, '', txt, re.I)
print txt

相关问题 更多 >