2016-11-22 82 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