23
loading...
This website collects cookies to deliver better user experience
string[start:stop:step]
# Python reverse a string using extended slice operator
def reverse(str):
str = str[::-1]
return str
text= "ItsMyCode"
print("The reversed string is :", reverse(text))
The reversed string is : edoCyMstI
for
loop. Each element in the string will be iterated using the for
loop, and then it appends the characters to the beginning of a new string to obtain a reversed string.# Python reverse a string using for loop
def reverse(s):
str = ""
for i in s:
str = i + str
return str
text = "ItsMyCode"
print("The reversed string is :", reverse(text))
The reversed string is : edoCyMstI
while
loop to reverse a string. We will determine the length of the string inside the while loop. We will join the characters from the end of the string and decrementing the count till it reaches 0.# Python reverse a string using while loop
def reverse(s):
str = ""
count = len(s)
while count > 0:
str += s[count - 1]
count = count - 1 # decrement index
return str
text = "ItsMyCode"
print("The reversed string is :", reverse(text))
The reversed string is : edoCyMstI
# Python reverse a string using recursion
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
text = "ItsMyCode"
print("The reversed string is :", reverse(text))
The reversed string is : edoCyMstI
reversed()
returns the reversed iterator of the given string, and then its elements are joined empty string separated using join()
. This approach will be the slowest approach when compared to the slicing approach.# Python reverse a string using reversed
def reverse(str):
str = "".join(reversed(str))
return str
text = "ItsMyCode"
print("The reversed string is :", reverse(text))
The reversed string is : edoCyMstI