The goal of my code is given a string, to separate the integer substrings from those containing solely alphabetical letters, with the individual substrings in a list.
For example:
- Input:
1h15min
- Output:
["1", "h", "15", "min"]
Here is the code:
def separate_text(input_text):
if not input_text:
return None
character_list = []
current_substring = ""
string_type = ""
for character in input_text:
if character in "0123456789":
if string_type in ("Int", ""):
current_substring += character
if string_type == "":
string_type = "Int"
else:
character_list.append(current_substring)
string_type = "Int"
current_substring = character
elif character not in "0123456789":
if string_type in ("Str", ""):
current_substring += character
if string_type == "":
string_type = "Str"
else:
character_list.append(current_substring)
string_type = "Str"
current_substring = character
character_list.append(current_substring)
return character_list
The function functions as follows:
- Take an input string (if empty, return
None
) - Begin looping through the string, character by character
- If the character is an integer
- If
string_type
isInt
or""
, append the character tocurrent_substring
and changestring_type
if needed - If
string_type
isStr
, append the substring to thecharacter_list
, reassigncurrent_substring
to whatever the character is, and change thestring_type
to"Int"
.
- If
- If the character is an string
- If
string_type
isStr
or""
, append the character tocurrent_substring
and changestring_type
if needed - If
string_type
isInt
, append the substring to thecharacter_list
, reassigncurrent_substring
to whatever the character is, and change thestring_type
to"Str"
.
- If
- End of the whole string? Append
current_substring
to the list and return thecharacter_list
.
My questions here are:
- Is there any way to make the program for Pythonic?
- Can I possible shorten my code? The two main
if
statements in thefor
loop have nearly identical code.
Note that I do not count floats so 1.15min
returns ['1', '.', '15', 'min']
.