从字符串中删除最后符

问题:从字符串中删除最后符

假设我的字符串长10个字符。

如何删除最后符?

如果我的字符串是"abcdefghij"(我不想替换'j'字符,因为我的字符串可能包含多个'j'字符),我只希望最后符消失。无论它是什么或发生多少次,我都需要从字符串中删除最后符。

Let’s say my string is 10 characters long.

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.


回答 0

简单:

st =  "abcdefghij"
st = st[:-1]

还有另一种方法可以显示如何通过步骤完成:

list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

这也是用户输入的一种方式:

list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

为了使它带走列表中的最后一个单词:

list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)

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)

回答 1

您正在尝试做的是Python 中字符串切片的扩展:

假设所有字符串的长度为10,最后符将被删除:

>>> st[:9]
'abcdefghi'

删除最后一个N字符:

>>> N = 3
>>> st[:-N]
'abcdefg'

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'