问题描述
我有一个列表,我尝试在其中使用循环删除特殊字符.当我尝试在没有循环的情况下删除那些特殊字符时,它起作用了.但是循环不起作用,但确实运行了(我不知道如何).这些特殊字符是:["和]".这可能是非常简单的事情或具有列表的理解能力,我尝试了一些但没有完全奏效(你如何在 Python 的列表理解中使用正则表达式? )
你能帮忙吗?我是 Python 新手,但它会很有帮助.请分享您的知识!
输出应该是:[ '1', '2' ]
我的代码:
导入重新# Case 1 : Sub 没有循环w = '[ 1,2,3,4 ]'外= re.compile("\[(.+)\]")m = 外部.search(w)inner_str = m.group(1)# 案例 2 - 带循环的 Subx = [ '[1]', '[2]' ]对于 x 中的项目:if item == re.match('\[(.+)\]', item):打印(re.sub("\[(.+)\]", "", item))
您可以使用列表推导式来做到这一点,您的意思是这样的吗?
>>>进口重新>>>x = [ '[1]', '[2]' ]>>>[re.sub(r'\W', '', i) for i in x]['1', '2']标记 \W
匹配任何非单词字符.
I have a list on which I try to remove special chars using a loop. When I've tried to remove those special chars without a loop, it worked. But with a loop didn't work, but did run (and I don't know how). Those special chars are :"[" and "]". It's probably something very simple or with list's comprehension, which I tried some but didn't quite work ( How do you use a regex in a list comprehension in Python? )
Could you help? I'm new to Python, but it would help a lot. Please share your knowledge!
Output should be : [ '1', '2' ]
My code:
import re
# Case 1 : Sub with no loop
w = '[ 1,2,3,4 ]'
outer= re.compile("\[(.+)\]")
m = outer.search(w)
inner_str = m.group(1)
# Case 2 - Sub with loop
x = [ '[1]', '[2]' ]
for item in x:
if item == re.match('\[(.+)\]', item):
print(re.sub("\[(.+)\]", "", item))
You can do this using a list comprehension, you mean something like this?
>>> import re
>>> x = [ '[1]', '[2]' ]
>>> [re.sub(r'\W', '', i) for i in x]
['1', '2']
The token \W
matches any non-word character.
这篇关于列表上的 re.sub - python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!