如何从字符串中删除最后一个字符?

"abcdefghij"  →  "abcdefghi"

当前回答

使用切片,可以指定开始和停止索引来提取字符串s的一部分。格式为s[start:stop]。缺省情况下,start = 0。我们只需要指定stop。


使用stop = 3:

>>> s = "abcd"
>>> s[:3]
'abc'

使用stop = -1从结尾删除1个字符(BEST METHOD):

>>> s = "abcd"
>>> s[:-1]
'abc'

使用stop = len(s) - 1:

>>> s = "abcd"
>>> s[:len(s) - 1]
'abc'

其他回答

这是最好的方法来删除最后一个字母或字符串,清洁代码,检查所有可能的错误

def RemoveLastOne(text): # RemoveLastOne function
    text = str(text) # convert type to str
    result = text[:(len(text)-1)] # remove last string
    return result #return result without last string

text = 'abcdefghij' #varible
result = RemoveLastOne(text) #input --> abcdefghij

print(result) #output --> abcdefghi

有一个叫做rstrip()的函数。输入要删除的值,在本例中是最后一个元素,即string[-1]:

string = "AbCdEf" 
newString = string.rstrip(string[-1])
print(newString)

如果你运行他的代码,你会看到'f'值被删除。

OUTPUT: AbCdE

使用切片,可以指定开始和停止索引来提取字符串s的一部分。格式为s[start:stop]。缺省情况下,start = 0。我们只需要指定stop。


使用stop = 3:

>>> s = "abcd"
>>> s[:3]
'abc'

使用stop = -1从结尾删除1个字符(BEST METHOD):

>>> s = "abcd"
>>> s[:-1]
'abc'

使用stop = len(s) - 1:

>>> s = "abcd"
>>> s[:len(s) - 1]
'abc'

最简单的解决方案是使用字符串切片。

Python 2/3:

source[0: -1]  # gets all string but not last char

Python 2:

source = 'ABC'    
result = "{}{}".format({source[0: -1], 'D')
print(result)  # ABD

Python 3:

source = 'ABC'    
result = f"{source[0: -1]}D"
print(result)  # ABD

你要做的是Python中字符串切片的扩展:

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

>>> st[:9]
'abcdefghi'

删除最后N个字符:

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