Python strings have no reverse() method, but a slice with a step of -1 reads the string from the last character to the first.
The program
python
text = input("Enter some text: ") reversed_text = text[::-1] print(reversed_text)
Typed in this example: Hello, World. Press Run to type your own.
output
Enter some text: Hello, World dlroW ,olleH
How it works
- A slice has three parts:
text[start:stop:step]. Here start and stop are left empty, so the slice covers the whole string. - A step of
-1moves backwards, one character at a time. Spaces and punctuation are characters too, so they move as well. - Strings cannot be changed in place.
text[::-1]makes a new string, andtextstays the same.
With a loop
This version builds the result one character at a time. Each new character goes in front of what is already there:
python
text = "Python" reversed_text = "" for ch in text: reversed_text = ch + reversed_text print(reversed_text)
output
nohtyP
Reverse the words, not the letters
To keep each word readable and change only their order, split the text into a list of words, reverse the list, and join it back together:
python
sentence = "learn it run it fix it" words = sentence.split() print(" ".join(reversed(words)))
output
it fix it run it learn