def trim(s): while True: if len(s)==0: return s elif s[0]==' ': s=s[1:] elif s[-1]==' ': s=s[0:-1] else: return s return s # 测试: if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!')
只比较了首个和最后一个元素,如果第2个,或倒数第2个是“ ”或“tab”键呢
while True 可以无限循环直到没有空格了
Sign in to make a reply
Neri.