Python 使用.replace和通配符删除列表中的文本
我有一个python格式的列表:Python 使用.replace和通配符删除列表中的文本,python,Python,我有一个python格式的列表: x = ['[a] 123', '[b] 456', '[c] 789'] 我想得到一份清单 xclean = ['123', '456', '789'] 我目前正试图用以下方法去除[*]'s: xclean=[] for item in x: cut_item = item.replace('[*]', '') xlistclean.append(cut_item) 认为*表示开始括号和结束括号之间的任何内容。相反,我得到了相同的列表,没
x = ['[a] 123', '[b] 456', '[c] 789']
我想得到一份清单
xclean = ['123', '456', '789']
我目前正试图用以下方法去除[*]'s:
xclean=[]
for item in x:
cut_item = item.replace('[*]', '')
xlistclean.append(cut_item)
认为*表示开始括号和结束括号之间的任何内容。相反,我得到了相同的列表,没有变化;可能是因为它正在搜索文本字符串“[*]”。
有没有更好的方法来实现这一点的想法?是的,常规的
str.replace
没有通配符功能。您可以使用带有通配符的re.sub
:
>>> import re
>>> x = ['[a] 123', '[b] 456', '[c] 789']
>>> x = [re.sub(r"\[.\] ", "", s) for s in x]
>>> print x
['123', '456', '789']
像这样的
x = ['[a] 123', '[b] 456', '[c] 789']
import re
def cleaner(list):
return [re.findall(r'] (\d+)',x)[0] for x in list]
xclean = cleaner(x)
试着更清楚地解释你的答案是什么,尤其是在这样的情况下,你正在引入初学者可能不熟悉的新功能(包括
re
模块)。请不要使用list
作为变量名,因为它隐藏了内置的list
类型。