网络编程
位置:首页>> 网络编程>> Python编程>> python如何删除字符串最后一个字符

python如何删除字符串最后一个字符

作者:yang  发布时间:2022-06-07 14:14:04 

标签:python,删除,字符串,字符

删除字符串最后一个字符的方法

1.使用strip()方法删除最后一个字符

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

  • strip()方法语法:str.strip([chars]);

  • 参数:chars – 移除字符串头尾指定的字符序列。

示例:

str = "0000000this is string example....wow!!!0000000";
print str.strip( '0' );

输出结果:

this is string example....wow!!!

2.将字符串转换为列表

然后使用pop()方法删除最后一个字符

a = 'abcd efg'
b = list(a) 
b.pop()
print(b)

输出结果如下:

['a', 'b', 'c', 'd', ' ', 'e', 'f']

去除字符串(去除前面几个或者是后面几个)

a = "16541616584984"
a = a[2:-2]
print(a)

输出结果:

5416165849

a[2:-2] 表示去掉前面两个和后面两个

如果光去掉后面的a[:-2]

去掉前面的操作以此类推。。。。

来源:https://www.py.cn/faq/python/17942.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com