string = "Hello world001"
end = []
last_change = string[-1].isdigit()
temp = []
for x in range(len(string)-1, -1, -1):
char = string[x]
changed = char.isdigit()
if changed==last_change:
temp.append(char)
continue
temp.reverse()
end.append("".join(temp))
temp = [char]
last_change = changed
if temp:
temp.reverse()
end.append("".join(temp))
end.reverse()
print(end)
This code wil split your string in chunks of letters and numbers but grouped together. I made it walk backwards through the 'string' so that if you need to differentiate between only last few digits and the rest, you can break the loop after first detected change.
Then your string part will be:
string_part = string[:x]
and the number:
number = end[-1]
# or "".join(temp) if you do not overwrite it
You can make it walk through the string forwards and remove all .reverse(), and also, discard range() and use:
for char in string: ...
This code is fast, no worries about that, but if you insist on even less code, then you can use regular expressions to do it. In module "re" there is re.split() function that is like normal str.split(), but splits by regexp pattern instead by the fixed substring. However, it is quite possible that for your purposes my code will be faster. re.split() will have to do much more checking along the way. Regexps are a terrific tool to have, if you know how to use them, but they aren't always the fastest solution there is.
I very much like the @schwobaseggl's answer. I would use the itertools solution if I were you. The groupby() function essentially works the same as the code I posted.