自定义函数去除字符串首尾的空格 def trim(s): if(s==''): return s else: for i in range(len(s)): if(s[0]!=' '): n = 0 elif(s[0:i]==' '*len(s[0:i])): n = i+1 if i==0 else i if(s[-1]!=' '): m = len(s) elif(s[i:]==' '*len(s[i:])): m = i break begin_str = n end_str = m s = s[begin_str:end_str] 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('测试成功!')