Home > Software engineering >  How would I print a string obtained from a user in reverse?
How would I print a string obtained from a user in reverse?

Time:12-11

I'm stuck on an exercise where I must obtain a string from a user and then print it in reverse with each letter on its own line. I've done this successfully with a for loop but I was wondering how to do so without it.

user_string = input("Please enter a string: ")  

for letter in (user_string)[::-1]:
    print(letter)

CodePudding user response:

If you know how many characters there are in the string or array (calculate using the length method len()) then you could do:

while i < arr_length:

with i incrementing at the end of every round.

The rest of the code would be the same but using i as an index.

CodePudding user response:

One method would be to cast the string to a list and use the list.pop() method until there are no characters left in the list.

user_input = list(input())
while len(user_input) > 0:
    print(user_input.pop())

list.pop() will remove the last item in the list and return it.

CodePudding user response:

def reverse(s): str = "" for i in s: str = i str return str

s = "Geeksforgeeks"

print("The original string is : ", end="") print(s)

print("The reversed string(using loops) is : ", end="") print(reverse(s))

CodePudding user response:

You can reverse and use str.join to rebuild the string.

print("\n".join(reversed(input("Please enter a string: "))))
  • Related