0

My goal is to recursively modify a string, such that if it is greater than 48 characters in length, the last word will be removed. If/once the string is not greater than 48 characters in length, return it.

This is my attempt:

def checkLength(str):
  if len(str) > 48:
    str = str.rsplit(' ',1)[0]
    checkLength(str)
  else:
    return str

Passing a string > 48 characters long results in an empty value.

What is the correct way to achieve this in Python, and why does the above function not work as one might expect?

Shane
  • 115
  • 1
  • 3
  • 17

1 Answers1

2
def checkLength(my_str):
  if len(my_str) > 48:
    my_str = str.rsplit(' ',1)[0]
    # you must return the recursive call! 
    return checkLength(my_str)
  else:
    return my_str
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179