简体   繁体   English

如何从列表中的某些字符串中删除特定字符串?

[英]How do I remove a specific string from some strings in a list?

I've been trying to figure out a more universal fix for my code and having a hard time with it.我一直在尝试为我的代码找出一个更通用的修复方法,并且很难使用它。 This is what I have:这就是我所拥有的:

lst = ['Thursday, June ##', 'some string', 'another string', 'etc', 'Friday, June ##', 'more strings', 'etc']

I'm trying to remove everything after the comma in the strings that contain commas (which can only be the day of the week strings).我正在尝试删除包含逗号的字符串中逗号之后的所有内容(只能是星期几字符串)。

My current fix that works is:我目前有效的修复方法是:

new_lst = [x[:-9] if ',' in x else x for x in lst]

But this won't work for every month since they're not always going to be a 4 letter string ('June').但这并不适用于每个月,因为它们并不总是一个 4 个字母的字符串('June')。 I've tried splitting at the commas and then removing any string that starts with a space but it wasn't working properly so I'm not sure what I'm doing wrong.我试过用逗号分割,然后删除任何以空格开头的字符串,但它不能正常工作,所以我不确定我做错了什么。

We can use a list comprehension along with split() here:我们可以在这里使用列表推导和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']

With regex :使用regex

>>> import re
>>> lst = [re.sub(r',.*', '', x) for x in lst]
>>> lst
['Thursday,', 'some string', 'another string', 'etc', 'Friday,', 'more strings', 'etc']

However, this is slower than the split answer但是,这比split答案慢

You can use re.search in the following way:您可以通过以下方式使用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)

Output:输出:

['Thursday', 'some string', 'another string', 'etc', 'Friday', 'more strings', 'etc']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM