Python 从字符串中删除最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15478127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove final character from string
提问by user1675111
Let's say my string is 10 characters long.
假设我的字符串长度为 10 个字符。
How do I remove the last character?
如何删除最后一个字符?
If my string is "abcdefghij"(I do not want to replace the 'j'character, since my string may contain multiple 'j'characters) I only want the last character gone. Regardless of what it is or how many times it occurs, I need to remove the last character from my string.
如果我的字符串是"abcdefghij"(我不想替换该'j'字符,因为我的字符串可能包含多个'j'字符)我只希望最后一个字符消失。无论它是什么或出现多少次,我都需要从我的字符串中删除最后一个字符。
回答by Cyrille
Simple:
简单的:
st = "abcdefghij"
st = st[:-1]
There is also another way that shows how it is done with steps:
还有另一种方式显示它是如何通过步骤完成的:
list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
This is also a way with user input:
这也是用户输入的一种方式:
list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
To make it take away the last word in a list:
让它去掉列表中的最后一个词:
list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)
回答by u1860929
What you are trying to do is an extension of string slicingin Python:
您要做的是在 Python 中扩展字符串切片:
Say all strings are of length 10, last char to be removed:
假设所有字符串的长度为 10,最后一个字符被删除:
>>> st[:9]
'abcdefghi'
To remove last Ncharacters:
删除最后一个N字符:
>>> N = 3
>>> st[:-N]
'abcdefg'

