Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string into a list (but not separating adjacent numbers) in Python

For example, I have:

string = "123ab4 5"

I want to be able to get the following list:

["123","ab","4","5"]

rather than list(string) giving me:

["1","2","3","a","b","4"," ","5"]
like image 956
Wrath Avatar asked Dec 27 '22 14:12

Wrath


1 Answers

Find one or more adjacent digits (\d+), or if that fails find non-digit, non-space characters ([^\d\s]+).

>>> string = '123ab4 5'
>>> import re
>>> re.findall('\d+|[^\d\s]+', string)
['123', 'ab', '4', '5']

If you don't want the letters joined together, try this:

>>> re.findall('\d+|\S', string)
['123', 'a', 'b', '4', '5']
like image 56
John Kugelman Avatar answered Dec 31 '22 14:12

John Kugelman