1

I have a list in python

a=['one_foo','two_foo','bar_foo']

Expected output:

['one','two','bar']

I tried doing by first converting list into string and then using regex

import re
re.sub("_.*$","", str(a))

I know converting list to string is incorrect way to achieve this task,may be is there any elegant way without converting it to string?

4
  • Are you tied to regex or are you willing to consider other solutions? Commented Oct 10, 2018 at 10:47
  • NO. we can use other solutions as well Commented Oct 10, 2018 at 10:47
  • What do you want to do with a string like "test_foo_bar"? Should the result be "test_foo" or "test" ? Commented Oct 10, 2018 at 10:50
  • @PM2Ring In that case the result should be "test_foo" (or just remove last string containing '_') Commented Oct 10, 2018 at 10:54

1 Answer 1

2

You can use a list comprehension with str.rsplit:

a = ['one_foo', 'two_foo', 'bar_foo']

res = [x.rsplit('_', 1)[0] for x in a]

['one', 'two', 'bar']

In general, regex solutions tend to underperform str methods for similar operations.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect solution!, but how rsplit is different with 'split'
split works from the left. rsplit works from the right. The 1 argument means we only perform one split.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.