Search code examples
pythonstringsplitdigits

how to use python re.split to split string but keep digits?


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.


Solution

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