0

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.

3 Answers 3

3

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']
Sign up to request clarification or add additional context in comments.

2 Comments

THANK YOU! This is perfect, much appreciated. What does the [0] do in the split method here?
split() returns a list, so the [0] is the first item in that list
0

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

2 Comments

Oh, thank you! I'm actually trying to remove the comma, how would I alter it to do so? Not familiar with regex
@bluetortuga, fixed. The second argument of re.sub is the replacement value. It's now nothing, so the comma will be removed
0

You can use re.search in the following way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.