我有一个列表,我尝试使用循环删除其中的特殊字符。当我尝试在没有循环的情况下删除这些特殊的字符时,它起作用了。但循环不起作用,但确实运行了(我不知道是如何运行的)。这些特殊字符是:"“和"”。它可能是非常简单的东西,或者是list的理解,我试过一些,但不是很有效( How do you use a regex in a list comprehension in Python? )
你能帮忙吗?我是Python的新手,但它会有很大帮助。请分享你的知识!
输出应为:“%1”,“%2”
我的代码:
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))发布于 2015-04-11 05:17:25
你可以使用列表理解来做这件事,你的意思是这样的吗?
>>> import re
>>> x = [ '[1]', '[2]' ]
>>> [re.sub(r'\W', '', i) for i in x]
['1', '2']标记\W可以匹配任何非单词字符。
发布于 2015-04-11 05:20:05
假设你想把东西放在括号里,这是可行的:
import re
# Case 1 : no sub!
w = '[ 1,2,3,4 ]'
outer= re.compile("\[(.+)\]")
m = outer.search(w)
inner_str = m.group(1)
print(inner_str)
# Case 2 - no sub!
x = [ '[1]', '[2]' ]
y = []
for item in x:
match = outer.match(item)
if match:
y.append(match.group(1))
print(y)https://stackoverflow.com/questions/29570771
复制相似问题