Python program to reverse a string
Description: Write a Python program to reverse a string in three different ways.
Rules and hints:
- Strings are immutable, so you create a new string.
Python program to reverse a string
text = "Python"
# 1. slicing
print(text[::-1])
# 2. reversed() and join()
print("".join(reversed(text)))
# 3. loop
result = ""
for ch in text:
result = ch + result
print(result)
Output:
Tutorials Class - Output Window
nohtyP
nohtyP
nohtyP
How it works
- Slicing with step
-1goes through the string from the end. reversed()gives the characters in reverse order, andjoin()makes a string again.- In the loop, every new character is added to the front of
result.
Related: join() function.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |