假设我的字符串长10个字符.
如何删除最后一个字符?
如果我的字符串是"abcdefghij"(我不想替换"j"字符.因为我的字符串可能包含多个"j"字符)我只希望最后一个字符消失.无论它是什么或发生了多少次,我都需要删除字符串中的最后一个字符.
Cyr*_*lle 736
简单:
st = "abcdefghij"
st = st[:-1]
Run Code Online (Sandbox Code Playgroud)
还有另一种方式可以显示如何通过以下步骤完成:
list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
Run Code Online (Sandbox Code Playgroud)
这也是用户输入的一种方式:
list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
Run Code Online (Sandbox Code Playgroud)
要删除列表中的最后一个单词:
list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)
Run Code Online (Sandbox Code Playgroud)
Nic*_*ico 12
最简单的解决方案是使用字符串切片。
Python 2/3:
source[0: -1] # gets all string but not last char
Run Code Online (Sandbox Code Playgroud)
Python 2:
source = 'ABC'
result = "{}{}".format({source[0: -1], 'D')
print(result) # ABD
Run Code Online (Sandbox Code Playgroud)
Python 3:
source = 'ABC'
result = f"{source[0: -1]}D"
print(result) # ABD
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)
To remove last N characters:
>>> N = 3
>>> st[:-N]
'abcdefg'
Run Code Online (Sandbox Code Playgroud)
使用切片,可以指定start和stop索引来提取字符串的一部分s。格式为s[start:stop]. 但是,start = 0默认情况下。所以,我们只需要指定stop.
使用stop = 3:
>>> s = "abcd"
>>> s[:3]
'abc'
Run Code Online (Sandbox Code Playgroud)
使用从末尾stop = -1删除字符(最佳方法):1
>>> s = "abcd"
>>> s[:-1]
'abc'
Run Code Online (Sandbox Code Playgroud)
使用stop = len(s) - 1:
>>> s = "abcd"
>>> s[:len(s) - 1]
'abc'
Run Code Online (Sandbox Code Playgroud)