Discuss / Python / 写了段递归去除多个空格,但是不知道为什么最后输出是None

写了段递归去除多个空格,但是不知道为什么最后输出是None

Topic source

def trim(s): if s[0] != ' ' and s[-1] != ' ': return s else: if s[0] == ' ': s = s[1:] if s[-1] == ' ': s = s[:-1] trim(s)

print(trim(' test '))

经过测试,如果参数本身没有空格就会正常输出,但是只要有一个空格都会输出None,不知道哪里有问题?求大神指教。。

加入了一个计数器来进行调试:

def trim(s, i=0): if s[0] != " " and s[-1] != " ": i +=1 print(i, "end") return s else: if s[0] == " ": i +=1 s = s[1:] print(i, s) if s[-1] == " ": i +=1 s = s[:-1] print(i, s) trim(s, i)

print(trim(" test "))

输出结果如下: 1 test
2 test 3 test 4 test 5 end None

说明中间过程是没问题的,到第四步也已经得到正确结果了,但是最后输出的还是None

自己解决了自己的问题。。╮(╯_╰)╭

因为平时看的课程,写递归函数时有的写成直接调用函数(比如我上面写的那样),有的用return print(), 有的用return 函数(这个网站的递归函数的章节为例),一直没思考他们的区别,结果就踩坑里了。。 实际上就是要写成return 函数 才能形成完整的调用回路,所以上面的代码把def内部的trim(s)改成return trim(s)就成功了。

def trim(s): if s[0] != ' ' and s[-1] != ' ': return s else: if s[0] == ' ': s = s[1:] if s[-1] == ' ': s = s[:-1] return trim(s)

print(trim(' test '))


  • 1

Reply