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?

jpp
  • 147,904
  • 31
  • 244
  • 302
deepesh
  • 1,576
  • 3
  • 14
  • 35

1 Answers1

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.

jpp
  • 147,904
  • 31
  • 244
  • 302