Write Python. Understand every error.

Open the editor

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

  1. Read the text.
  2. Slice it with a step of -1.
  3. Print the result.

The program

text = input()
print(text[::-1])

Sample run

Input
python
Output
nohtyp

Run this program in Py-CRAFT

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

Common mistakes

Learn the ideas

More programs

Share this page: