我想从一个字符串中删除每个元素。例如:S =“ABCDE”现在我想删除第一个“E”,然后“d”,直到s是空的。
您可以使用切片:
s = 'abcde'
for i in range(len(s), 0, -1):
print(s[:i])
您应该使用切片运算符为:
s='abcde'
for i in range(len(s), -1, -1):
s = s[:i]
print(s)
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'