您的位置:首页 > 编程语言 > Python开发

12python切片实现trim()

2020-01-14 09:08 423 查看

12python切片实现trim()

利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法

strip()方法

用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

test = "000python000world000"print(test.strip("0"))

运行结果

python000world

正解1:利用循环更替字符

def trim(s):while s[:1] == " ":     # 判断第一个字符是否为空格,若为真利用切片删除这个字符s = s[1:]while s[-1:] == " ":    # 判断最后一个字符是否为空格,若为真利用切片删除这个字符s = s[:-1]return stest = "   python   "print(trim(test))

运行结果

python

正解2:利用切片判断后递归

def trim(s):if s[:1] == " ":		# 判断第一个字符是否为空格s = trim(s[1:])		# 利用递归改变S并再次进行判断if s[-1:] == " ":		# 判断最后一个字符是否为空格s = trim(s[:-1])	# 利用递归改变S并再次进行判断return stest = "   python   "print(trim(test))

运行结果

python

容易写错的方法

def trim(s):while s[0] == " ":s = s[1:]while s[-1] == " ":s = s[:-1]return stest = "  python  "print(trim(test))

运行结果

python

这里看似没有任何问题,我们成功的定义了一个trim()函数并实现其功能
但经过不断的尝试,终于发现了问题
当我们传入一个空字符时程序会报错

def trim(s):while s[0] == " ":s = s[1:]while s[-1] == " ":s = s[:-1]return stest = ""print(trim(test))

运行结果

Traceback (most recent call last):File "E:/pycharm/homeWork12.py", line 27, in <module>print(trim(test))File "E:/pycharm/homeWork12.py", line 20, in trimwhile s[0] == " ":IndexError: string index out of range

索引器错误:字符串索引超出范围
而我们使用之前的正确方式则不会报错

def trim(s):while s[:1] == " ":s = s[1:]while s[-1:] == " ":s = s[:-1]return stest = ""print(trim(test))

运行结果(空,不报错)

究其原因我认为是s[0]和s[:1]的区别所导致的
当序列是空序列,这时候用[:1]取第一个元素是空,不会报错,而用[0]取由于超过索引范围则会报错

  • 点赞
  • 收藏
  • 分享
  • 文章举报
py自学实践发布了41 篇原创文章 · 获赞 2 · 访问量 859私信关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐