How do I split a string into a list?


If I have this string:


what is the most efficient approach for creating this list:

['2', '+', '24', '*', '48', '/', '32']

By : Larsenal


You can use split from the re module.

re.split(pattern, string, maxsplit=0, flags=0)

Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.

Example code:

import re
data = re.split(r'(\D)', '2+24*48/32')


When the UNICODE flag is not specified, \D matches any non-digit character; this is equivalent to the set [^0-9].

By : Readonly

>>> import re
>>> my_string = "2+24*48/32"
>>> my_list = re.findall(r"-?\d+|\S", my_string)
>>> print my_list

['2', '+', '24', '*', '48', '/', '32']

This will do the trick. I have encountered this kind of problem before.

This video can help you solving your question :)
By: admin