删除字符串最后一个字符的方法
1.使用strip()方法删除最后一个字符
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
- strip()方法语法:str.strip([chars]);
- 参数:chars – 移除字符串头尾指定的字符序列。
示例:
1
2
|
str = "0000000this is string example....wow!!!0000000" ; print str .strip( '0' ); |
输出结果:
this is string example....wow!!!
2.将字符串转换为列表
然后使用pop()方法删除最后一个字符
1
2
3
4
|
a = 'abcd efg' b = list (a) b.pop() print (b) |
输出结果如下:
['a', 'b', 'c', 'd', ' ', 'e', 'f']
去除字符串(去除前面几个或者是后面几个)
1
2
3
|
a = "16541616584984" a = a[ 2 : - 2 ] print (a) |
输出结果:
5416165849
a[2:-2] 表示去掉前面两个和后面两个
如果光去掉后面的a[:-2]
去掉前面的操作以此类推。。。。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://www.py.cn/faq/python/17942.html