Home > Mobile >  How do I remove a specific string from some strings in a list?
How do I remove a specific string from some strings in a list?

Time:05-17

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'). 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.

Thank you in advance for helping!

CodePudding user response:

We can use a list comprehension along with split() here:

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']

CodePudding user response:

With 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

CodePudding user response:

You can use a list comprehension.

new_list = [i[:i.find(',')] for i in lst]

This assumes you don't want the commas. If you want the comma, you can use

new_list = [i[:i.find(',') 1] for i in lst]
  • Related