我有一个从单词末尾删除标点符号的功能
def clean(word):
if word[-1].isalpha():
return word.lower()
else:
word = word[:-1]
clean(word)
如果我跑,例如,print(clean('foo!!!'))
该函数会打印None
。但是,如果我在函数中将return
更改为print
:
def clean(word):
if word[-1].isalpha():
print(word.lower())
else:
word = word[:-1]
clean(word)
然后该函数打印foo
。为什么return
和print
之间存在差异?
答案 0 :(得分:1)
更改你的功能,以便它可以进行递归调用:
def clean(word):
if word[-1].isalpha():
return word.lower()
else:
word = word[:-1]
return clean(word)