python 如何去掉字符串最后一位 Python如何删除字符串的最后3个字符

python\u600e\u4e48\u628a\u5b57\u7b26\u4e32\u6700\u540e\u4e00\u4e2a\u5b57\u7b26\u53bb\u6389

python\u628a\u5b57\u7b26\u4e32\u6700\u540e\u4e00\u4e2a\u5b57\u7b26\u53bb\u6389\u7684\u65b9\u6cd5\uff1a
def DelLastChar(str): str_list=list(str) str_list.pop() return "".join(str_list)new_str=DelLastChar("abcdx")print new_str\u6700\u540e\u4e24\u884c\u662f\u6d4b\u8bd5\uff0c\u8fd9\u4e2a\u51fd\u6570\u7684\u4f5c\u7528\u5c31\u662f\u5220\u9664\u5b57\u7b26\u4e32\u7684\u6700\u540e\u4e00\u4e2a\u5b57\u7b26\u3002
\u601d\u8def\u5c31\u662f\uff0c\u5c06\u5b57\u7b26\u4e32\u6253\u6563\u4e3a\u4e00\u4e2alist\uff0c\u7136\u540epop\u51fa\u8fd9\u4e2alist\u7684\u6700\u540e\u4e00\u4e2a\u5143\u7d20\uff0c\u7136\u540e\u518d\u5c06\u8fd9\u4e2alist\uff0c\u6574\u5408join\u4e3a\u4e00\u4e2a\u5b57\u7b26\u4e32\u3002

Python\u5220\u9664\u5b57\u7b26\u4e32\u7684\u6700\u540e3\u4e2a\u5b57\u7b26\u7684\u65b9\u6cd5\uff1a
1\u3001\u5148\u5c06\u5b57\u7b26\u4e32\u8f6c\u6362\u6210\u5217\u8868\uff0c\u4e4b\u540e\u518d\u4fee\u6539\u5217\u8868\u4e2d\u7684\u5143\u7d20\u6765\u5b8c\u6210\uff0c\u901a\u8fc7list(r)\u6765\u5c06r\u5b57\u7b26\u4e32\u8f6c\u5316\u6210\u4e86\u4e00\u4e2a\u5217\u8868\u3002

2\u3001\u7136\u540e\u4fee\u6539\u5355\u4e2a\u5217\u8868\u7684\u5143\u7d20\uff0c\u5c06\u7b2c\u4e8c\u4e2a\u5143\u7d20d\u66ff\u6362\u6210\u4e86m\u3002

3\u3001\u6700\u540e\u901a\u8fc7join\u7684\u65b9\u6cd5\u628a\u5217\u8868\u4e2d\u7684\u5143\u7d20\u5408\u6210\u4e00\u4e2a\u5b57\u7b26\u4e32\u3002

4\u3001\u901a\u8fc7python\u81ea\u5e26\u7684replace\u65b9\u6cd5\u76f4\u63a5\u5b8c\u6210\u66ff\u6362\uff0c\u5c06\u5b57\u7b26\u4e32\u4e2d\u7684\u5b57\u7b26a\u66ff\u6362\u6210\u4e86A\u3002

5\u3001\u5176\u6b21\u8fd9\u4e2areplace\u4e5f\u53ef\u4ee5\u66ff\u6362\u5b57\u7b26\u4e32\u4e2d\u7684\u591a\u4e2a\u5b57\u7b26\u3002

6\u3001replace\u65b9\u6cd5\u6bd4\u8f83\u8bd5\u7528\u4e8e\u66ff\u6362\u5b57\u7b26\u4e32\u4e2d\u7684\u591a\u4e2a\u76f8\u540c\u7684\u5b57\u7b26\uff0c\u66ff\u6362\u4e5f\u6bd4\u8f83\u7b80\u5355\u5feb\u6377\u3002

1
2
3
4
5
6

def DelLastChar(str):
str_list=list(str)
str_list.pop()
return "".join(str_list)
new_str=DelLastChar("abcdx")
print new_str

最后两行是测试,这个函数的作用就是删除字符串的最后一个字符。

思路就是,将字符串打散为一个list,然后pop出这个list的最后一个元素,然后再将这个list,整合join为一个字符串。

扩展阅读:python 删除重复字符串 ... python字符串怎么清空 ... python 删除一段字符串 ... 输入一个非空字符去除重复 ... python删除指定字符串 ... python分割字符串split ... python去除多余空格 ... python 字符串删除元素 ... python去除字符串重复元素 ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网