Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

5 Expert Techniques to Reverse Strings in Python

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:

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:

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:

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:

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:

Conclusion

Summarize this post with:


Python

  1. Master Python’s str.count(): How to Count Characters & Substrings with Examples
  2. Master Python `format()` Strings with Clear Examples
  3. Mastering Python datetime: Practical Guide to Dates, Times, and Timezones
  4. Enforce a Minimum Python Version in Your Script
  5. Master Python's strptime() for Accurate Date Parsing
  6. Python Counter in collections – Efficient Counting, Updating, and Arithmetic Operations
  7. How to Remove Items from a Python List: remove(), pop(), clear(), and del
  8. Python Network Programming: Master Sockets & Advanced Protocols
  9. Python Variable Types: Understanding and Using Data Types
  10. Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes