'Python: Print string in reverse
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
then the output is:
ereht olleH
yeH
I have already the code like this. I don't understand what I have done wrong. Please help.
word = str(input())
the_no_word = ['Done', 'done', 'd']
while word == "Done" and word == "done" and word == "d":
break
print(word[-1::-1])
Solution 1:[1]
This may work for you:
word = ""
the_no_word = ['Done', 'done', 'd']
while word not in the_no_word:
word = str(input())
print(word[-1::-1])
You need to get the user input into word
after every loop and check if word is not in the list of the_no_word
. Let me know if this is what you were looking for.
Solution 2:[2]
string=input('enter a string :')
words=string.split()
for x in words:
print(x[::-1],end=' ')
here first i defined a string which stores the input then is use split function to split the string where space is there and returns a list of it the a traverse words and then i print x in reverse order if you still face problem in split fuction i have given statement print(words) see the output of it you will undrstand it
Solution 3:[3]
You could do it like this:
while (word := input()) not in ['Done', 'done', 'd']:
print(word[::-1])
Solution 4:[4]
var1 = str(input())
bad_word = ['done', 'd', 'Done']
while var1 not in bad_word:
print(var1[::-1])
var1 = str(input())
Just did the problem and used this answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Richard |
Solution 2 | Sahil Panhalkar |
Solution 3 | Albert Winestein |
Solution 4 |