Splitting Text and Numbers in a String with Python
Without regular expression
2 min readNov 17, 2023
Many times when working with strings, you might feel the need to separate text from numbers. As I was surfing through programming guides, I found that achieving this using regular expressions is fairly straightforward.
However, if you are like me, you might find regular expressions unreasonably difficult. Therefore, I came up with a simple algorithm that does the job.
Please feel free to look at the code and take a moment to see if the explanation below makes sense to you.
def split_text_from_digit(string):
result = []
text = ''
digit = ''
prev_char = None
for char in string:
if char.isdigit():
if prev_char == "digit" or prev_char==None:
digit+=char
else:
if text != '':
result.append(text)
text = ''
digit = ''
digit+=char
prev_char = "digit"
else:
if prev_char == "text" or prev_char==None:
text+=char
else:
if digit != '':
result.append(digit)
digit = ''
text = ''
text+=char…