Python - Reverse Slicing of given string
Last Updated : 14 Jan, 2025
Improve
Reverse slicing in Python is a way to access string elements in reverse order using negative steps.
Using Slicing ([::-1]
)
Using slicing with [::-1]
in Python, we can reverse a string or list. This technique works by specifying a step of -1
, which starts at the end of the sequence and moves backward, effectively reversing the order of elements. It's a concise and efficient way to reverse strings or lists.
s1 = "hello"
s2= s1[::-1]
print(s2)
Output
Reversed String: olleh
Explanation
- The slicing syntax
[::-1]
starts at the end of the string and moves backward with a step of-1
.
Using a Loop
Using a loop to reverse a string involves iterating through each character in reverse order and building a new string.
s1 = "hello"
s2 = ""
for char in s1:
s2 = char + s2
print("Reversed String:", s2)
Output
Reversed String: olleh
Explanation
- Each character is added to the front of the result string, effectively reversing the order.