Python trim()切片函数去除首尾空格

def trim(s):
   if len(s) == 0:  # 字符串为空直接返回
      return ''
   elif s[0] != ' ' and s[-1] != ' ':  # 首尾不存在空格直接返回
      return s
   elif s[0] == ' ':  # 字符串头存在空格则截断
      return trim(s[1:])
   else:
      return trim(s[:-1])  # 字符串尾存在空格则截断
if trim('hello  ') != 'hello':
   print('测试失败')
elif trim('  hello') != 'hello':
   print('测试失败')
elif trim('  hello word  ') != 'hello word':
   print('测试失败')
elif trim(' ') != '':
   print('测试失败')
elif trim('    ') != '':
   print('测试失败')
else:
   print('测试成功')

猜你喜欢

转载自blog.csdn.net/u013274257/article/details/84256827