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!
>Solution :
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']