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
- The first way uses a slice. The second builds a new string by putting each letter in front of the ones already there.
split()breaks a sentence into a list of words, and" ".join(...)puts them back together.- Three different ways to do the same job is normal in programming: pick the clearest.
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
Hello world and variables
Print a message, store things in variables and join them together.
Beginner ยท ages 8+Even or odd
Say whether each number from 1 to 10 is even or odd.
Beginner ยท ages 8+FizzBuzz
Count from 1 to 20. For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for both print FizzBuzz.
Easy ยท ages 9+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
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.
Pick a game
- Code BuilderThe lines of a Python program are mixed up. Tap them into the rightโฆPlay
- Bug HunterA Python program prints the wrong answer. Find the one line with theโฆPlay
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay