I am trying to split a string of arbitrary length into chunks of 3 characters. I know this question has been asked previously (How do you split a list into evenly sized chunks?), but that answer solves the problem with a list comprehension; I'm trying to solve the problem using a recursive function call, so my question is more about recursive functions calls in Python.
My function works fine until the "base case", the very last string of 3 or less characters. I am getting a TypeError: can only concatenate list (not "NoneType") to list
.
Why is the base case returning None
instead of a list
? I explicitly create a list called final_value
in the base case and return that. I even have a debugging print statement that shows me that the base case return value is of type <class 'list'>
.
My code is below.
three_char_strings = []
def split3(str):
if len(str) <= 3:
final_value = []
final_value.append(str)
print('Final value: %s\nFinal value type: %s\n' % (final_value, type(final_value))) #For debugging
return final_value
else:
beginning = str[0:3]
three_char_strings.append(beginning)
remaining = str[3:]
three_char_strings + split3(remaining)