【Pthon入门学习】利用slice实现str的strip函数,类似C#中的string.trim

1.先了解下切片的知识点

切片是str, list,tuple中常用的取部分元素的操作。

例如:

  1 L =['北京', '上海', '天津', '深圳', '石家庄']
  2 print(L[0:2]) # 从第0的索引位置开始到第2个索引位置,但是不包括第2个索引位置。类似数学中的集合半闭半开[)
  3 print(L[:-1]) # 支持倒序>len(L) - 1的索引位置等于-1的索引;即len(L) - i的索引位置等于-i的索引

2.实现trim函数

方法一:采用一个循环同时从str的开始和结束的索引位置向中间遍历,遇到非空的结束。记录下顺序遍历和倒序遍历的位置,然后使用slice返回部分字符串

  1 def trim(s):
  2     s_len = len(s)
  3     low_move = True
  4     low = 0
  5     high = s_len
  6     high_move = True
  7     for i in range(s_len):
  8         if s[i] != ' ' and s[s_len - i - 1] != ' ':
  9             break
 10 
 11         if low_move and s[i] == ' ':
 12             low = i + 1
 13         else:
 14             low_move = False
 15 
 16         if high_move and s[s_len - i - 1] == ' ':
 17             high = s_len - i - 1
 18         else:
 19             high_move = False
 20     return s[low:high]
View Code

方法二:采用一个循环同时从str的开始和结束的索引位置向中间遍历,遇到空字符,直接利用slice改变该字符串,去掉空字符。

  1 def trim(s):
  2     s_len = len(s)
  3     for i in range(s_len):
  4         if s[:1] == ' ':
  5             s = s[1:]
  6         if s[-1:] == ' ':
  7             s = s[:-1]
  8     return s
View Code


3. 验证函数是否正确

  1 # 测试:
  2 if trim('hello  ') != 'hello':
  3     print('1测试失败!')
  4 elif trim('  hello') != 'hello':
  5     print('2测试失败!')
  6 elif trim('  hello  ') != 'hello':
  7     print('3测试失败!')
  8 elif trim('  hello  world  ') != 'hello  world':
  9     print('4测试失败!')
 10 elif trim('') != '':
 11     print('5测试失败!')
 12 elif trim('    ') != '':
 13     print('6测试失败!')
 14 else:
 15     print('7测试成功!')
View Code
原文地址:https://www.cnblogs.com/yongqiangyue/p/8805948.html