Reverse a String in Python
Python slicing provides a concise way to read a sequence from the end to the beginning.
What is Reverse a String?
Python slicing provides a concise way to read a sequence from the end to the beginning.
Reverse a Python string with slicing and run the example online.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
main.py
message = "CodeUtility"
reversed_message = message[::-1]
print(reversed_message)
Expected output
ytilitUedoC
How it works
The slice [::-1] uses the complete string with a negative step, so the characters are returned in reverse order.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.