Sunday, 1 April 2018

Python:Reverse a String using 5 Different Ways


Reverse String in Python: Using 5 Different Ways:
=====================================

Python string library does’nt support the in-built “reverse()” as done by other python containers like list, hence knowing other methods to reverse string can prove to be useful.

1.Using Loop:

# Python code to reverse a string
# Methon1: Using loop

def reverse(s):
  str = ""
  for i in s:
    str = i + str
  return str

s = "ManishBidsar"

print ("The original string  is : ",end="")
print (s)

print ("The reversed string(Methon1:Using loop) is : ",end="")
print (reverse(s))


Output:
======
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
  
The original string  is : ManishBidsar
The reversed string(Methon-1:Using loop) is : rasdiBhsinaM



Explanation: In above code, we call a function to reverse a string, which iterates to every element and intelligently join each character in the beginning so as to obtain the reversed string.

2.Using Recursion:

# Python code to reverse a string
# Method2:Using recursion

def reverse(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]

s = "MANISHBIDSAR"

print ("The original string  is : ",end="")
print (s)

print ("The reversed string(Method2:Using recursion) is : ",end="")
print (reverse(s))

Output:
======
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
  
The original string  is : MANISHBIDSAR
The reversed string(Method2:Using recursion) is : RASDIBHSINAM


Explanation: In the above code, string is passed 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, the string is returned. 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.

3.Using Extended Slice Syntax:

# Python code to reverse a string
# Method3:Using extended slice syntax

# Function to reverse a string
def reverse(string):
    string = string[::-1]
    return string

s = "MANISHBIDSAR"

print ("The original string  is : ",end="")
print (s)

print ("The reversed string(Method3:Using extended slice syntax) is : ",end="")
print (reverse(s))

Output:
======

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
  
The original string  is : MANISHBIDSAR
The reversed string(Method3:Using extended slice syntax) is : RASDIBHSINAM



Explanation: Extended slice offers to put a “step” field as [start,stop,step], and giving no field as start and stop indicates default to 0 and string length respectively and “-1” denotes starting from end and stop at the start, hence reversing string.


4.Using reversed:

# Python code to reverse a string
# Method4:Using reversed()

# Function to reverse a string
def reverse(string):
    string = "".join(reversed(string))
    return string

s = "ManishBidsar"

print ("The original string  is : ",end="")
print (s)

print ("The reversed string(Method4:Using reversed is : ",end="")
print (reverse(s))

Output:
======
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
  
The original string  is : ManishBidsar
The reversed string(Method4:Using reversed is : rasdiBhsinaM

Explanation: The reversed() returns the reversed iterator of the given string and then its elements are joined empty string separated using join(). And reversed order string is formed.

  
5.Using Stack:
# Python code to reverse a string
# Method5:Using Stack

# Function to create an empty stack. It
# initializes size of stack as 0
def createStack():
    stack=[]
    return stack
 
# Function to determine the size of the stack
def size(stack):
    return len(stack)
 
# Stack is empty if the size is 0
def isEmpty(stack):
    if size(stack) == 0:
        return true
 
# Function to add an item to stack . It
# increases size by 1   
def push(stack,item):
    stack.append(item)
 
# Function to remove an item from stack.
# It decreases size by 1
def pop(stack):
    if isEmpty(stack): return
    return stack.pop()
 
# A stack based function to reverse a string
def reverse(string):
    n = len(string)
     
    # Create a empty stack
    stack = createStack()
 
    # Push all characters of string to stack
    for i in range(0,n,1):
        push(stack,string[i])
 
    # Making the string empty since all
    # characters are saved in stack   
    string=""
 
    # Pop all characters of string and put
    # them back to string
    for i in range(0,n,1):
        string+=pop(stack)
         
    return string

# Driver code
s = "ManishBidsar"
print ("The original string  is : ",end="")
print (s)
print ("The reversed string(Method5:Using Stack) is : ",end="")
print (reverse(s))

Output:
======
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
  
The original string  is : ManishBidsar
The reversed string(Method5:Using Stack) is : rasdiBhsinaM
  

Explanation: An empty stack is created. One by one characters of string are pushed to stack.
One by one all characters from stack are popped, and put them back to string.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.