Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading