0

I have a string of names that is comma delimited and some of the names have an abbreviation after such as the following:

"major league baseball, national football league (nfl), major league soccer" ... 

I want to place a comma before the parenthesis (before any opening parenthesis) so I can use string split. I tried using the following regex but doesn't quite do what I want.

result = re.split(",()", result)
nick
  • 789
  • 1
  • 11
  • 27
  • 1
    Does `s = s.replace("(", ",(")` work? – kgf3JfUtW Nov 02 '17 at 16:29
  • I think this initial way worked as well, I realized there's a problem with my string (for some reason there are commas just after all opening parenthesis) and causing behavior I didn't expect – nick Nov 02 '17 at 16:35

2 Answers2

3

Use replace instead of a regex:

In [1]: s = "major league baseball, national football league (nfl), major league soccer (mls)"

In [2]: s.replace('(', ',(').split(',')
Out[2]:
['major league baseball',
 ' national football league ',
 '(nfl)',
 ' major league soccer ',
 '(mls)']
salparadise
  • 5,699
  • 1
  • 26
  • 32
1

You want to do this before split:

result = result.replace(' (', ', ').replace(')', '')
#"major league baseball, national football league, nfl, major league soccer"
halfer
  • 19,824
  • 17
  • 99
  • 186
zipa
  • 27,316
  • 6
  • 40
  • 58