比较菜的写法
Topic sourcedef trim(s):
# 尝试递归 首先清除首位空格
while len(s) > 0 and s[0] == ' ':
s = trim(s[1:])
while len(s) > 0 and s[-1] == ' ':
s = trim(s[:-1])
return s
s = input('one str:')
a = trim(s)
试了一下,你这个递归是不需要的吧,while已经保证你的循环了,直接s = s[1:]这样就可以了。
如果要用递归的话或许可以用if?(说错勿怪,初学者
def trim(m): if m == '': return m elif m[0] == ' ' and len(m) > 0: s1 = m[1:] return trim(s1) elif m[-1] == ' ' and len(m) > 0: s2 = m[:-1] return trim(s2) else: return m
- 1
sober°_
def trim(nn):
l = len(nn)
if nn[0] == ' ' and nn[l-1] == ' ':
nn_1 = nn[1:l-1]
elif nn[0] == ' ':
nn_1 = nn[1:l]
elif nn[-1] == ' ':
nn_1 = nn[:l-1]
else:
nn_1 = nn
return nn_1