2016-11-22 83 views
0

我的目标是递归修改一个字符串,如果长度大于48个字符,最后一个字将被删除。如果/一旦该字符串的长度不超过48个字符,则将其返回。Python:递归修改字符串

这是我的尝试:

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

传递一个字符串> 48个字符长的结果为空值。

在Python中实现这个功能的正确方法是什么?为什么上述功能不能像预期的那样工作?

+1

另外,不要使用'str'作为变量名,它会隐藏内置类型。 –

+0

感谢您的提示!我将铭记未来。 – Shane

回答

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