Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I separate characters and numbers in a string

Tags:

python

string

I would like to know how do I separate characters and numbers in a string and return it as an array

Eg:

"abc123" -> ["abc","123"]

"1a2bc2" -> ['1','a','2','bc','2']

"1bdc3" -> ['1','bdc','3']

Thank you for taking your time and answer me

like image 690
Gato Avatar asked Jun 11 '26 06:06

Gato


1 Answers

import itertools

def separate(string):
    return ["".join(group) for key, group in itertools.groupby(string, str.isdigit)]

print(separate("abc123"))
print(separate("1a2bc2"))
print(separate("1bdc3"))
like image 93
Alex Hall Avatar answered Jun 13 '26 09:06

Alex Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!