How to reverse a string in Python

You may need to deal with reverse a string in Python if you use them frequently in your code. Python has a number of useful tools and strategies that can assist you in these circumstances. You’ll be able to rapidly and easily create reversed duplicates of existing strings with them.

Knowing how to reverse strings in Python using these tools and approaches can help you enhance your skills as a Python programmer.

Strings are order sequences of character data in Python. A built-in technique for reversing a string, i-e: “reverse()” does not exist. Strings, on the other hand, can be reverse in a variety of ways.

You’ll learn how to do the following in this tutorial:

  • Slicing allows you to quickly create reversed strings.
  • Using reversed() and .join(), make reversed copies of existing strings.
  • To manually reverse existing strings, use iteration and recursion.
  • Iterate your strings in the other direction.
  • Using sorted, sort your strings in reverse order ()

In some situations, working with Python strings in reverse order may be necessary. Let’s imagine you have the string “ABCDEF” and want to quickly reverse it to get “FEDCBA.” What Python tools do you have at your disposal to assist you?

Because Python strings are immutable, reversing a given string in situ is not feasible. To achieve the criteria, you’ll need to make reversed duplicates of your target strings.

img1

Methods of reverse a string in Python

There are five different methods to reverse a string are explain below:

1) Using Loop in Python – reverse a string in Python

s = "SoftHunt"    # initial string
reversedString=[ ]
index = len(s)     # calculate length of string and save in index
while index > 0:
reversedString += s[ index - 1 ]   # save the value of str[index-1] in reverseString
index = index - 1   # decrement index
print(reversedString)   # reversed string

Output:

['t', 'n', 'u', 'H', 't', 'f', 'o', 'S']

Explanation: To start, let’s create a new array called reversedString[]. We can then loop over the list with iterating variable index initialized with the length of the list.

  • Concatenate the value of str[index-1] with reverseString in each iteration. 
  • Decrement the index. 

After that, we just iterate till the index is less than zero.

2) Using Recursion in Python

def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
s = "SoftHunt"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using recursion) is : ",end="")
print (reverse(s))

Output:

The original string is : SoftHunt
The reversed string(using recursion) is : tnuHtfoS

Explanation: The string is supply as an argument to a recursive function in the above code to reverse the string. The base condition of the function is that the string is return if the length of the string is equal to 0. If the value is not 0, the reverse function is use recursively to slice the string except for the first character and concatenate the first character to the end of the sliced string.

3) Using Stack in Python

def createStack():
stack=[ ]
return stack
def size(stack):
return len(stack)
def isEmpty(stack):
if size(stack) == 0:
return true
def push(stack,item):
stack.append(item)
def pop(stack):
if isEmpty(stack): return
return stack.pop()
def reverse(string):
n = len(string)
stack = createStack()
for i in range(0,n,1):
push(stack,string[i])
string=""
for i in range(0,n,1):
string+=pop(stack)
return string
s = "SoftHunt"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using stack) is : ",end="")
print (reverse(s))

Output:

The original string is : SoftHunt
The reversed string(using stack) is : tnuHtfoS

Explanation: The stack is generate empty. String characters are push to the top of the stack one by one. All characters from the stack are pop one by one and returned to the string.

4) Using Extended Slice Syntax in Python

def reverse(string):
string = string[::-1]
return string
s = "SoftHunt"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using extended slice syntax) is : ",end="")
print (reverse(s))

Output:

The original string is : SoftHunt
The reversed string(using extended slice syntax) is : tnuHtfoS

Explanation: Extended slice allows you to specify a “step” field as [start, stop, step], with no field indicating that start and stop are set to 0 and string length, respectively, while “-1” implies starting from the end and stopping at the beginning, reversing the string.

5) Using Reversed

def reverse(string):
string = "".join(reversed(string))
return string
s = "SoftHunt"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using reversed) is : ",end="")
print (reverse(s))

Output:

The original string is : SoftHunt
The reversed string(using reversed) is : tnuHtfoS

Explanation: The reversed() method returns the reversed iterator of the provided string, which is then merged with an empty string using join (). As a result, a reversed order string is created.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Leave a Comment