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

list, python, string

Solution

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']

Problem

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"] ```

Original source