Book a free demo

Beginner ยท ages 9+ ยท strings ยท slicing ยท loops

Reverse a string in Python.

Turn a sentence round in three different ways.

The program

Press Run to see what it prints. Change anything you like, then run it again.

text = "coding is fun"
print(text[::-1])

backwards = ""
for letter in text:
    backwards = letter + backwards
print(backwards)

words = text.split()
print(" ".join(reversed(words)))
nuf si gnidoc
nuf si gnidoc
fun is coding

How it works

  1. The first way uses a slice. The second builds a new string by putting each letter in front of the ones already there.
  2. split() breaks a sentence into a list of words, and " ".join(...) puts them back together.
  3. Three different ways to do the same job is normal in programming: pick the clearest.
See the Python path โ†’

Try this

  • Reverse each word but keep the word order.
  • Write a function called reverse.
  • Check which way is shortest.

Stuck on an error? Read how to debug Python.

Similar ideas

More programs

All programs โ†’

FAQ

Reverse a string: questions

What does the reverse a string program do?

Turn a sentence round in three different ways. It prints: nuf si gnidoc / nuf si gnidoc / fun is coding

Which Python ideas does it use?

strings, slicing, loops. Beginner level, suitable from about age 9.

How do I run it?

Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.

What should I try next?

Reverse each word but keep the word order. Write a function called reverse. Check which way is shortest.

Start a conversation

Want a teacher to guide the learning?

Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.

  • Tell us the learnerโ€™s age or grade and goals
  • Weโ€™ll suggest a suitable class or learning path
  • Weโ€™ll confirm format, timing and fees with a parent or guardian

For a childโ€™s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

Weโ€™ll use your details only to respond to this request.

Play it, don't just read it

Write some code right now

Free games that need no sign-up. Pick one and play for five minutes.

All free games โ†’
Chat on WhatsApp
Esc

Try