Problem
We would like to turn upside down a string and print it in reverse mode in Python.
Solution
We have many different methods to approach to reverse a string in Python. Let’s look at each technique one by one in this post.
Using Extended Slicing technique:
We can obtain with the reverse of a string by applying the slicing technique [::-1]. Let’s work with an example.
Code:
def getreversed(value):
return value[::-1]
samplestring = "Let's reverse it"
print("String:",samplestring)
print("Reverse String:",getreversed(samplestring))
Output:
String: Let's reverse it
Reverse String: ti esrever s'teL
Using recursive function technique:
We can create a recursive function, slice the first value and return the string every time to obtain a reverse string value.
Code:
def getreversed(value):
if len(value) == 0:
return value
else:
return getreversed(value[1:]) + value[0]
samplestring = "Let's get it reversed"
print("String:",samplestring)
print("Reverse String:",getreversed(samplestring))
Output:
String: Let's get it reversed
Reverse String: desrever ti teg s'teL
Using For loop method:
Initially, we assign an empty string. Using For loop, we loop through each letter and store it in the empty string. The returned value would be the reversed string.
Code:
def getreversed(value):
str = ""
for i in value:
str = i + str
return str
samplestring = "Get it reversed"
print("String:",samplestring)
print("Reverse String:", getreversed(samplestring))
Output:
String: Get it reversed
Reverse String: desrever ti teG
Using Join function:
By using the ”.join(reversed(‘string’)) we can easily reverse the string.
Code:
def getreversed(value):
return ''.join(reversed(value))
samplestring = "This is going to be reversed"
print("String:",samplestring)
print("Reverse String:", getreversed(samplestring))
Output:
String: This is going to be reversed
Reverse String: desrever eb ot gniog si sihT