如何从字符串中删除最后一个字符?
"abcdefghij" → "abcdefghi"
如何从字符串中删除最后一个字符?
"abcdefghij" → "abcdefghi"
简单:
my_str = "abcdefghij"
my_str = my_str[:-1]
尝试下面的代码片段,以更好地理解它是如何通过将字符串转换为列表工作的:
str1 = "abcdefghij"
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)
在这种情况下,你想接受用户的字符串:
str1 = input("Enter :")
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)
让它从句子中去掉最后一个单词(单词之间用空格分隔):
str1 = input("Enter :")
list1 = str1.split()
print(list1)
list2 = list1[:-1]
print(list2)
你要做的是Python中字符串切片的扩展:
假设所有字符串的长度为10,最后一个字符将被删除:
>>> st[:9]
'abcdefghi'
删除最后N个字符:
>>> N = 3
>>> st[:-N]
'abcdefg'
最简单的解决方案是使用字符串切片。
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
使用切片,可以指定开始和停止索引来提取字符串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'
有一个叫做rstrip()的函数。输入要删除的值,在本例中是最后一个元素,即string[-1]:
string = "AbCdEf"
newString = string.rstrip(string[-1])
print(newString)
如果你运行他的代码,你会看到'f'值被删除。
OUTPUT: AbCdE
这是最好的方法来删除最后一个字母或字符串,清洁代码,检查所有可能的错误
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