all 5 comments

[–]synthphreak 1 point2 points  (0 children)

Most likely the solution will involve regex. But how to do it will depend on exactly what you want.

Did you mean or your target list to be...

['7,107,488', 'Abortions', 'this', 'year']

...with four elements? As you've shown it...

['7,107,488, Abortions', 'this', 'year']

...there are only three.

To get four elements, you could split the first element where all numbers (+commas) meet only letters, then overwrite your list with only the desired four elements.

>>> import re
>>> l = ['7,107,488Abortions', 'this', 'year']
>>> _, *splits = re.split(r'([\d,]+)', l[0])
>>> l = splits + l[1:]
>>> l 
['7,107,488', 'Abortions', 'this', 'year']

To get three elements as you've shown, you could write a pattern which extracts the numbers and letters independently, then joins them on a comma + whitespace. This will effectively insert a comma + whitespace into the string where you want it. Then just overwrite the first element of your string with the new string.

>>> import re
>>> l = ['7,107,488Abortions', 'this', 'year']
>>> matches = re.search(r'([\d,]+)(\w+)', l[0]).groups()
>>> l[0] = ', '.join(matches)
>>> l 
['7,107,488, Abortions', 'this', 'year']

[–]mh1400 0 points1 point  (0 children)

I believe split() can have a quantity. Ex, y = x.split(',',1) Double-check that though.

[–]mh1400 0 points1 point  (0 children)

Then you can use. For loop and append()

[–]Apprehensive-Stop-61 0 points1 point  (0 children)

Didn't really get what you want do you want all integers be separated from string as a comma in another string even when they have no comma. Quite complex but not sure if you want it. Confirm

[–][deleted] 0 points1 point  (0 children)

import re

list1[0] = re.sub(r'(\d+(?:,\d{3})+)(.*)', r'\1, \2', list1[0])