There is no built-in function as such to how to reverse a string in python. The most common way developers reverse a string is by slicing it backward. Python has several handy techniques and tools which can help the user in these situations. The user is then able to build revere replicas of the strings very fast and efficiently. There are a lot of ways to reverse a string in python. We will talk about them in the sections below:
Python program to reverse a string using slicing
txt = "Welcome to Develoepr Helps"[::-1]
print(txt)
Output
spleH rpeoleveD ot emocleW
In the above example, we have created a slice which is starting at the end of the string and moves backward.
The slice statement which is used is [::-1]
. It means slicing will start at the end of the string and end at position 0, move with the step -1
, negative one, which means one step backwards.
Python String Reverse using recursion
Initially, a string passes as an argument to a recursive function to reverse the string. In the function, the base condition is that if the length of the string is equal to 0, it returns the string. If not equal to 0, the reverse function is recursively called to slice the part of the string except the first character and concatenate the first character to the end of the sliced string.
Let us see an example below to understand the reversal of a string better-using recursion:
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
s = "Welcome to Developer Helps"
print ("The actual string is : ",end="")
print (s)
print ("The string after reversal will be: ",end="")
print (reverse(s))
Output
The actual string is : Welcome to Developer Helps
The string after reversal will be: spleH repoleveD ot emocleW
Python program to reverse a string using function
If the user wishes to have a function where he can send the string and then return it backward, he can use a function to do this. Let us see an example below to understand the reversal of a string.
def my_function(x):
return x[::-1]
txt = my_function("Welcome to Developer Helps")
print(txt)
Output
spleH repoleveD ot emocleW
Python Program to reverse a string using for loop
def reverse(str):
str1 = ""
for i in str:
str1 = i + str1
return str1
str = "Welcome to Developer Helps"
print("The actual string is: ",str)
print("The reversed string is: ",reverse(str))
Output
The actual string is: Welcome to Developer Helps
The reversed string is: spleH repoleveD ot emocleW
In the above code, The user has declared the reverse() function and passed the str argument to it. In the function body, he has declared an empty string variable str1 that will hold the reversed string. Next, the for loop iterated every element of the given string, join each character in the beginning, and store it in the str1 variable. After the complete iteration, it returned the reverse order string str1 to the caller function. Hence result prints.