![](/img/trans.png)
[英]How do I remove specific characters on all strings of a list in python?
[英]How do I remove a specific string from some strings in a list?
我一直在嘗試為我的代碼找出一個更通用的修復方法,並且很難使用它。 這就是我所擁有的:
lst = ['Thursday, June ##', 'some string', 'another string', 'etc', 'Friday, June ##', 'more strings', 'etc']
我正在嘗試刪除包含逗號的字符串中逗號之后的所有內容(只能是星期幾字符串)。
我目前有效的修復方法是:
new_lst = [x[:-9] if ',' in x else x for x in lst]
但這並不適用於每個月,因為它們並不總是一個 4 個字母的字符串('June')。 我試過用逗號分割,然后刪除任何以空格開頭的字符串,但它不能正常工作,所以我不確定我做錯了什么。
我們可以在這里使用列表推導和split()
:
lst = ['Thursday, June ##', 'some string', 'another string', 'etc', 'Friday, June ##', 'more strings', 'etc']
output = [x.split(',', 1)[0] for x in lst]
print(output)
# ['Thursday', 'some string', 'another string', 'etc', 'Friday', 'more strings', 'etc']
使用regex
:
>>> import re
>>> lst = [re.sub(r',.*', '', x) for x in lst]
>>> lst
['Thursday,', 'some string', 'another string', 'etc', 'Friday,', 'more strings', 'etc']
但是,這比split
答案慢
您可以通過以下方式使用re.search
:
import re
lst = ['Thursday, June ##', 'some string', 'another string', 'etc', 'Friday, June ##', 'more strings', 'etc']
for i, msg in enumerate(lst):
match = re.search(",", msg)
if match != None:
lst[i] = msg[:match.span()[0]]
print(lst)
輸出:
['Thursday', 'some string', 'another string', 'etc', 'Friday', 'more strings', 'etc']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.