Discuss / Python / 为什么我的总是失败?

为什么我的总是失败?

Topic source

while s[0:1]=='': s=s[1:] while s[-1:]=='': s=s[:-1] return (s)

这个要用到回掉递归; def trim(s): if s == " ": return s elif s[:1] == " ": return trim(s[1:]) elif s[-1:] == " ": return trim(s[:-1]) else: print(s)

print('去除首尾空格-----') trim(' 123654 ')

你要使用回掉递归: def trim(s): if s == " ": return s elif s[:1] == " ": return trim(s[1:]) elif s[-1:] == " ": return trim(s[:-1]) else: print(s)

print('去除首尾空格-----') trim(' 123654 ')

亭风_

#4 Created at ... [Delete] [Delete and Lock User]

大兄弟。。。你的‘’之间没有加一个空格,应该写成‘ ’,这样就OK啦

while len(s) > 0 and s[0:1] == ' ':
    s = s[1:]
while len(s) > 0 and s[-1] == ' ':
    s = s[:-1]
return s

晴天菜鸟

#6 Created at ... [Delete] [Delete and Lock User]

大兄弟。。。你的‘’之间没有加一个空格,应该写成‘ ’,这样就OK啦


  • 1

Reply