从字符串中删除最终字符(Python)

use*_*111 445 python string

假设我的字符串长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)

  • `[i [: - 1] for i in ['blue','red','green']]` (5认同)
  • 查看示例,值得一提的是列表是可变的,并且“list.pop()”方法是处理列表时的最佳方法,因为它会删除“O(1)”中的最后一项,而`[:-1]` 切片会在 `O(n-1)` 时间加上 `O(n-1)` 空间中创建一个没有最后一个元素的列表副本。字符串是不可变的——因此无需添加任何内容。 (5认同)
  • 实际上,即使`st`为空,切片仍然有效.好吧,它仍将返回一个空字符串,但你不会收到错误. (4认同)
  • 是的,“ st [-1]”只是“ st”的最后一个字符 (3认同)
  • 如果您有一个单词列表并且想要删除每个单词的最后一个字符怎么办?[蓝色、红色、绿色] => [蓝色、红色、绿色] ? (2认同)

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)


mu *_*u 無 6

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)


Mat*_*haq 6

使用切片,可以指定startstop索引来提取字符串的一部分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)