[python] (递归, 切片)去除字符串首尾空格
1 def trim(s): 2 if s[:1] == ' ': 3 return trim(s[1:]) 4 if s[-1:] == ' ': 5 return trim(s[:-1]) 6 return s 7 8 # 测试: 9 if trim('hello ') != 'hello': 10 print('测试失败!') 11 elif trim(' hello') != 'hello': 12 print('测试失败!') 13 elif trim(' hello ') != 'hello': 14 print('测试失败!') 15 elif trim(' hello world ') != 'hello world': 16 print('测试失败!') 17 elif trim('') != '': 18 print('测试失败!') 19 elif trim(' ') != '': 20 print('测试失败!') 21 else: 22 print('测试成功!')
本文来自博客园,作者:泥烟,CSDN同名, 转载请注明原文链接:https://www.cnblogs.com/Knight02/p/16042967.html