Python program to reverse a string
In this post, you will learn how to reverse a string using the Python programming language.
Such a type of question is generally asked in a programming interview. The interviewer may demand to write different approaches to reverse a string, as they may ask you to use an inbuilt method or use a recursive method. Solving such problems can improve your logical skills and make you perfect for coding challenges. In Python programming, there are different ways to reverse a string. Here, we have mentioned most of them.
Python reverse a string using slicing
We can reverse a string using slicing. For this, we simply create a slice that starts at the length of the string and ends at the zero index. It moves one step backward, i.e., -1.
def rev_string(x):
return x [::-1]
revTxt = rev_string("Welcome to etutorialspoint")
print(revTxt)
Output of the above code
tniopslairotute ot emocleW
Python reverse a string using a for loop
Here is the Python program to reverse a given string using a for loop. The given string passes through the for loop statement. We have defined a variable and, in each iteration of the loop, the characters of the string are appended to the variable in reverse order.
def rev_str_for_loop(s):
revTxt = ''
for x in s:
# appending chars in reverse order
revTxt = x + revTxt
return revTxt
string = 'Success is journey not a destination'
if __name__ == "__main__":
print('Reverse string using for loop:', rev_str_for_loop(string))
Output of the above code
Reverse string using for loop: noitanitsed a ton yenruoj si sseccuS
Python reverse a string using while loop
In the given example, we reverse the string using a while loop. First, we create a function rev_str_while_loop(). Next, we take the length of the input string and subtract it by 1, because the index in Python starts from 0. In the while loop, we check if the calculated length is greater than or equal to zero. Next, we add the new string to the iterated character and reduce the length by 1. Once the length is less than zero, the while loop gets completed, and we get the result.
def rev_str_while_loop(s):
ch = ''
length = len(s) - 1
while length >= 0:
ch = ch + s[length]
length = length - 1
return ch
string = 'Find a small win each day'
if __name__ == "__main__":
print('Reverse string using while loop:', rev_str_while_loop(string))
Output of the above code
Reverse string using while loop: yad hcae niw llams a dniF
Reverse a string using recursion
A recursion function is a function that is called by itself. In the given example, we have called the recursion function to find the reverse of a string. A recursion function continues until some condition is met to prevent it. That's why we use the if statement to break the infinite recursion.
def rev_string(s):
if len(s) == 0:
return s
else:
return rev_string(s[1:]) + s[0]
string = 'Never give up'
if __name__ == "__main__":
print('Reverse string using recursion:', rev_string(string))
Reverse a string using join() and reversed()
In the given example, we have used the join() method with the reversed() method to find the reverse of a string. The reversed() method returns the reversed iterator of the given string and then its elements are joined into an empty string separated using join() and the string is formed in reversed order.
string = 'etutorialspoint'
reversedstring =''.join(reversed(string))
print("Reverse string using join : ",end="")
print(reversedstring)
Output of the above code
Reverse string using join : tniopslairotute
Related Articles
Convert a string to a float in Python
Casefold in Python
isalpha Python
Python split multiple delimiters
Replace multiple characters Python
Python multiline string
Alphabet pattern programs in Python
Python remove punctuation from string
Remove character from string Python
Count vowels in a string python
Count occurrences of each character in string Python
Convert string to list Python
Python split multiple delimiters
Python program to reverse a string
Permutation of string in Python
Remove spaces from string Python
splitlines in python
Python program to sort words in alphabetical order
Python split string by comma
Remove character from string Python
Check if two strings are anagrams Python