0

Reverse string in Python in different ways

Reverse string in Python in different ways

Reverse string in Python in different ways – Python’s string library does not support built-in “reverse ()” like other Python wrappers, such as lists, so it can be helpful to understand other methods for reversing strings. This article introduces 5 different ways to invert strings in Python, so let’s get started.

1. using for loop

CODE:
def reverse(string):
str = ""
for i in range(len(string)-1,-1,-1):
str += string[i]
return str

str = "shaadcoding"
print("ORIGINAL STRING : ",str)
print("REVERSED STRING USING FOR LOOP : ",reverse(str))
OUTPUT:
ORIGINAL STRING :  shaadcoding
REVERSED STRING USING FOR LOOP : gnidocdaahs

2. using while loop

CODE:
def reverse(string):
i = len(string) - 1
str = ""
while i >= 0:
str += string[i]
i -= 1
return str
OUTPUT:
ORIGINAL STRING :  shaadcoding
REVERSED STRING USING WHILE LOOP : gnidocdaahs

3. using slice[] operator

CODE:
def reverse(string):
string = string[::-1]
return string
OUTPUT:
ORIGINAL STRING :  shaadcoding
REVERSED STRING USING SLICE[] : gnidocdaahs

4. using reversed() and join() function

CODE:
def reverse(string):
s = "".join(reversed(string))
return s
OUTPUT:
ORIGINAL STRING :  shaadcoding
REVERSED STRING USING reversed() AND join() function : gnidocdaahs

5. using recursion

CODE:
def reverse(string):
length = len(string)
if length == 0:
return string
else:
return reverse(string[1:]) + string[0]
OUTPUT:
ORIGINAL STRING :  shaadcoding
REVERSED STRING USING RECURSION:  gnidocdaahs

If you have another effective way to do this task. Regarding reverse strings in Python, please share them in the comments section.

You can also use Python or any other language. Share it in the comment section to help others

keep visiting : shaadcoding

shaad

Leave a Reply

Your email address will not be published. Required fields are marked *