I was building a bit of code that would trim off any non-digit entries from the start and end of a string, I had a very confusing issue with the following bit of code:
def String_Trim(Raw_String):
if Raw_String[0].isdigit() == False:
New_String = Raw_String[1:]
String_Trim(New_String)
elif Raw_String[-1].isdigit() == False:
New_String = Raw_String[:-1]
String_Trim(New_String)
else:
print Raw_String
return Raw_String
print(String_Trim('ab19fsd'))
The initial printing of Raw_String works fine and displays the value that I want (19), but for some reason, the last line trying to print the return value of String_Trim returns a None. What exactly is python doing here and how can I fix it? Any other comments about improving my code would also be greatly appreciated.
Use regex for this. Recursion for trimming a string is really not a good idea:
To break it down, the regex (
r'^([^0-9]+)(.*?)([^0-9]+)$') is like so:^matches the start of a string.([^0-9]+)matches a group of consecutive non-digit characters.(.*?)matches a group of stuff (non-greedy).([^0-9]+)matches another group of consecutive non-digit characters.$matches the end of the string.The replacement string,
r'\2', just says to replace the matched string with only the second group, which is the stuff between the two groups of non-digit characters.But if you’re really sure you want to use your existing solution, you need to understand how recursion actually works. When you call
return foo, the function returnsfooas its output. If you don’t callreturn, you returnNoneautomatically.That being said, you need to
returnin every case of the recursion process, not just at the end: