[英]Python - removing characters from a list
我有這樣的元素列表:
['1:{test}', '2:{test}', '4:{1989}', '9:{test}', '']
我的問題是:
如何從此列表的元素中刪除特定字符?
結果,我想要擁有:
['test', 'test', '1989', 'test', '']
有什么建議,解決方案嗎?
提前致謝。
>>> re.findall(r'\{(.*)\}', '1:{test}')
['test']
只需使其循環即可:
[(re.findall(r'\{(.*)\}', i) or [''])[0] for i in your_list]
或者可能:
[''.join(re.findall(r'\{(.*)\}', i)) for i in your_list]
您可以使用正則表達式,如下所示:
import re
s = re.compile("\d+:{(.*)}")
data = ['1:{test}', '2:{test}', '4:{1989}', '9:{test}', '']
result = [s.match(d).group(1) if s.match(d) else d for d in data]
結果是
['test', 'test', '1989', 'test', '']
Python的strip()
函數正是這樣做的-從字符串的末尾刪除特定的字符-但是可能有更好的方法來執行所需的操作。
您沒有確切說出模式是什么,或者沒有括號時想要什么,但這在您的示例中有效:
stripped = []
for x in my_data:
m = re.search("{.*}", x)
stripped.append(m.group if m else x)
t = ['1:{test}', '2:{test}', '4:{1989}', '9:{test}', '']
map(lambda string: re.search(r'(?<=\{).+(?=\})', string).group(0), t)
當然,這不是最合理的格式,也不是最容易閱讀的答案。 這將一個匿名函數映射為查找並返回括號內的內容到列表的每個元素,並返回整個列表。
(?<=...)
意思是“僅匹配開頭具有此名稱的內容,但不要將其包含在結果中
(?=...)
意思是“僅匹配結尾處有此內容的匹配項,但不要將其包含在結果中
.+
表示“至少任何一種字符”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.