Reputation: 477
I'm a python learner. I want to use python re.split() to split a string into individual characters, but I don't want to split digits.
Example: s = "100,[+split"
The result should be ["100", ",", "[", "+", "s", "p", "l", "i", "t"]
I tried to use re.split(r'[A-Za-z]+|\d+', s)
and re.findall(r'[0-9]+]|\d+', s)
, but I'm really not good at using those methods. Can someone help me? Much appreciated.
Upvotes: 0
Views: 342
Reputation: 71461
You can use re.findall
:
import re
s = "100,[+split"
new_s = re.findall('\d+|[a-zA-Z\W]', s)
Output:
['100', ',', '[', '+', 's', 'p', 'l', 'i', 't']
Upvotes: 1
Reputation: 13965
[re.search('\d*', s).group()] + [val for val in s if not val.isdigit()]
This gets you the desired output for this particular string, but without knowing more about what types of string you are expecting it is hard to say if it will work in all cases.
This works by searching the string for numbers, and then adding to that a list of all the characters that are not numbers.
Output is:
['100', ',', '[', '+', 's', 'p', 'l', 'i', 't']
Upvotes: 0