如何从Python中的字符串中删除每一个元素?

问题描述 投票:-5回答:3

我想从一个字符串中删除每个元素。例如:S =“ABCDE”现在我想删除第一个“E”,然后“d”,直到s是空的。

python
3个回答
0
投票

您可以使用切片:

s = 'abcde'
for i in range(len(s), 0, -1):
    print(s[:i])

0
投票

您应该使用切片运算符为:

s='abcde'
for i in range(len(s), -1, -1):
    s = s[:i]
print(s)

Output: ''


0
投票
s = 'abcde'
c = list(s) # this line converts the string to array of 
                  # characters [ 'a', 'b', 'c', 'd', 'e'] 


while c:   # loop till array is empty
  c.pop() # Retrieve elements from the array end and 
                # remove it from array 

输出:

'e'
'd'
'c'
'b'
'a'
© www.soinside.com 2019 - 2024. All rights reserved.