方法一:
# -*- coding: utf-8 -*- # 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法: def trim(s): while s[:1] == ‘ ‘: s = s[1:] while s[-1:] == ‘ ‘: s = s[0:-1] 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(‘测试成功!‘)
方法二:
(此方法会有一个问题,当字符串仅仅是一个空格时‘ ’,会返回return s[1:0];虽然不会报错,但是会比较奇怪。测试了下,当s=‘abc’时,s[1:0]=‘’ 空值)
# -*- coding: utf-8 -*- def trim(s): i = 0 j = len(s) - 1 while i < len(s): if s[i] == ‘ ‘: i = i + 1 else: break while j > -1: if s[j] == ‘ ‘: j = j - 1 else: break return s[i:j+1] # 测试: 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(‘测试成功!‘)
原文地址:https://www.cnblogs.com/chling/p/11758075.html
时间: 2024-12-29 10:13:53