I have tried to modify the code to print the reverse of banana but I still can't find a solution. thanks in advance.
index = 0
fruit = "banana"
while index < len(fruit):
letter = fruit[index]
print (letter)
index = index 1
CodePudding user response:
This works
fruit = "banana"
index = len(fruit)
while index > 0:
letter = fruit[index-1]
print (letter)
index = index -1
But I strongly recommend you to check and understand how string indexing works.
CodePudding user response:
fruit = "banana"
rev_fruit = fruit[::-1]
print(rev_fruit)
#output: ananab
CodePudding user response:
Try this approach. In Python -1 means last position, so the len of the word (negative) is the first position of your slice.
Because Python range is not inclusive, you have to add a -1 to this scenario. Otherwise it it will print "anana".
Finally, we want to go from -1 to -6, so the increment must be -1.
word = "banana"
start = -1
end = (len(word) * -1) - 1
increment = -1
print(word[start:end:increment])