Home > Back-end >  I am trying to write a program that prints out the input string in reversed order from end to beginn
I am trying to write a program that prints out the input string in reversed order from end to beginn

Time:07-18


    string = str(input("Please type in a string: "))
    index = 0
    while index < len(string):
        print(string[index])  
        index  = -1 

I am getting an error that says (string index out of range)

CodePudding user response:

The reason you are getting 'Index out of range' error is that your while condition will never be false since you're index will almost always be less than 0.

This should fix that:

string = str(input())
index = len(string) - 1;  # Start at the end of your string
while index > -1:         # Until you have reached the end
    print(string[index])  
    index -= 1            # Equivalent to 'index  = -1' but cleaner

CodePudding user response:

strings in python are kinda like lists. You can use print(string[::-1]) to print backwards

Edit:

To print character by character

string = string[::-1]
index=0
while index < len(string):
    print(string[index])
    index  = 1
  • Related