Python programs · Strings
Python program to reverse a string
Reversing a string is often the first string exercise. Python does it with one slice.
Approach
- Read the text.
- Slice it with a step of -1.
- Print the result.
The program
text = input() print(text[::-1])
Sample run
Input
python
Output
nohtyp
How the code works
The slice [::-1] means: the whole string, stepping backwards one character at a time. Strings cannot be changed in place, so this builds a new string. Another way is a loop that adds each character to the front of a result: reversed_text = ch + reversed_text.
Try changing it
- Reverse the order of the words instead of the letters with
" ".join(text.split()[::-1]). - Do it with a loop and compare the two methods.
Common mistakes
- Expecting
text.reverse()to work. That method belongs to lists, not strings. - Writing
text[-1], which gives only the last character.