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 |
|---|
| Python Strings |
| Exercises & Assignments |
|---|
| Python program to check palindrome string |
| Python program to count vowels in a string |
| Python program to reverse a string |
| Interview Questions & Answers |
|---|
| How would you convert a string into lowercase? |
| How would you convert a string into uppercase? |
| Why do we use the join() function in Python? |
| What are f-strings in Python? |