How to reverse a String in Python (5 Methods)
A string is an ordered list or a sequence of characters. Strings are one of the data structures that comes with Python. As you are working with strings in Python, you might want to have all the characters reversed. A good example would be when you are building a palindrome game.
A reversed string has its first character as the last character and so on. However, Python does not come with a built-in function for reversing strings, but they are methods you can use.
In this tutorial, you’ll learn different methods to reverse the string in Python.
Method 1: Reverse string in Python using a For Loop
The first method for reversing strings is using a for loop as in the code snippet below:
Python Code:
# function for reversing a string def reverse_string(string): # an empty string for storing reversed string reversed_string = "" # looping through the string for char in string: # reversing the string reversed_string = char + reversed_string # returning a reversed string return reversed_string # the string to reverse string = "Guru99" # printing a message print(f"String Reversal using a for loop") # printing the original string print(f"Original String: {string}") # making a functional call inside a print function using an f-string print(f"Reversed String: {reverse_string(string)}")
Output:
String Reversal using a for loop Original String: Guru99 Reversed String: 99uruG
Code Explanation:
- In this code snippet, we can use reverse_string() function for string reversal taking a given string as an argument.
- Inside it, we can create an empty string to store the reversed string, then we are looping through the string.
- The characters are reversed and assigned to the reversed_string variable.
- Finally, the last line in the function returns the reversed string.
- To display the output, are making a functional call inside the print() function with the help of an f-string.
Method 2: Reverse string in Python using a While Loop
Using a while loop in Python would also be another method for reversing a string. Let us understand the code snippet below:
Python Code:
# declaring a string to reverse string = "Python" # initializing an empty string to store the reversed string reversed_string = "" # printing a message print(f"String Reversal using a while loop") # printing the original string print(f"Original String: {string}") # find length of a string and store in count variable count = len(string) # a while loop for looping through the string characters while count > 0: # save the value of str[count-1] in reversed_string reversed_string += string[count - 1] # decrementing index count = count - 1 print(f"Reversed String: {reversed_string}")
Output:
String Reversal using a while loop Original String: Python Reversed String: nohtyP
Code Explanation:
- In this Python code, we are declaring a string to be reversed, then an empty string to store the reversed string.
- We are then finding the string length which is assigned to the count variable.
- The string[count – 1] in every iteration retrieves the string characters from last to first.
- And concatenates them to reversed_string and then decrements the count value.
- Finally, we are printing the reversed string.
Method 3: Python Reverse String using Slicer Operator
Another method for reversing a string is using a slice operator, to get your head around it, see the code below:
Python Code:
# function to reverse a string def reverse(string): # the slice syntax reversed_string = string[::-1] return reversed_string # declaring a string to reverse string = "Let's guru99" # printing a message print(f"String Reversal using Slicer Operator") # printing the original string print(f"Original String: {string}") # making a functional call inside a print function using an f-string print(f"Reversed String: {reverse(string)}")
Output:
String Reversal using Slicer Operator Original String: Let's guru99 Reversed String: 99urug s'teL
Code Explanation:
- To create a reverse() function which takes a string as an argument, inside it
- In this example, we have a string[::-1] slice operator for reversing the string
- Then the reversed string is assigned to a new variable called reversed_string
- Finally, the new reversed string is returned
Method 4: Reversing a String in Python using the reversed() Function
We can also reverse a string using a reversed() Python function, the code would look as follows:
Python Code Example:
# function to reverse a string def reverse(string): # reversed() function inside the join() function string = "".join(reversed(string)) # returning the reversed string return string # declaring a string to reverse string = "guru99" # printing a message print(f"String Reversal using reversed() function") # printing the original string print(f"Original String: {string}") # making a functional call inside a print function using an f-string print(f"Reversed String: {reverse(string)}")
Output:
String Reversal using reversed() function Original String: guru99 Reversed String: 99urug
Code Explanation:
- In this code, we have a reversed() function whose argument is a string.
- Inside it, we have initialized an empty string.
- We concatenate it with the output of reversed(string) using the join() function.
- Outside the reversed() function, we have declared a string to reverse, then we are printing the original string and the reversed string.
Method 5: Python Reverse String using Recursion
Recursion means a defined function calling itself. A recursive function is said to be recursive when it calls itself. To understand it better look at the following code example:
Python Code:
# a function to reverse a string def reverse(string): # Checking the length of string if len(string) == 0: return string # reversing string if len(string) != 0 else: # recursively calling the reverse() function return reverse(string[1:]) + string[0] # declaring a string to reverse string = "I love guru99" # printing a message print(f"String Reversal using Recursion") # printing the original string print(f"Original String: {string}") # making a functional call inside a print function using an f-string print(f"Reversed String: {reverse(string)}")
Output:
String Reversal using Recursion Original String: I love guru99 Reversed String: 99urug evol I
Code Explanation:
- In the above code, we have declared a reverse () function that takes a string as an argument, the body of the function is an if else statement.
- The if statement checks whether the string length is equivalent to 0 and returns the string, while the else statement calls the reverse() function recursively, slices the last index of the string, and adds it to the start.
Conclusion
- This Python tutorial has walked you through reversing strings using various methods in Python.
- We can use reverse_string() function for string reversal taking a given string as an argument.
- You can use also use “for and while loop” for reverse stirring.
- You can sue reversed function that takes a string as an argument.
- When choosing these methods, you should consider their performance as one of the factors.