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
  • 159,742
  • 34
  • 281
  • 339
Andre_k
  • 1,680
  • 3
  • 18
  • 41

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
  • 159,742
  • 34
  • 281
  • 339