user5802211 user5802211 - 7 days ago 4
Python Question

python how to split string with more than one character?

I would like to split a string as below

1234ABC
into
123
and
ABC


2B
into
2
and
B


10E
into
10
and
E


I found
split
function does not work because there is no
delimiter

Answer

You can use itertools.groupby with boolean isdigit function.

from itertools import groupby

test1 = '123ABC'
test2 = '2B'
test3 = '10E'

def custom_split(s):
    return [''.join(gp) for _, gp in groupby(s, lambda char: char.isdigit())]

for t in [test1, test2, test3]:
    print(custom_split(t))

# ['123', 'ABC']
# ['2', 'B']
# ['10', 'E']