I want to remove each element from a string. For example: s= "abcde" now I want to remove first "e" then "d" till s is empty.
You can use slices:
s = 'abcde'
for i in range(len(s), 0, -1):
print(s[:i])
You should use slice operator as:
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
Output:
'e'
'd'
'c'
'b'
'a'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.