DEV Community 👩‍💻👨‍💻

Saiyam Jain
Saiyam Jain

Posted on

5 ways to reverse a string in Python

Hello everyone, in this post I will provide you 5 different ways to reverse a string using python programming.

1

Using Slicing

def StrRev(string):
    string = string[::-1]
    return string

s = input("Enter a string: ")

print (StrRev(s))
Enter fullscreen mode Exit fullscreen mode

2

Using Reversed Function

def StrRev(string):
    string = "".join(reversed(string))
    return string

s = input("Enter a string: ")
print (StrRev(s))
Enter fullscreen mode Exit fullscreen mode

3

Using Loop

def StrRev(s):
  strg = ""
  for i in s:
    strg = i + strg
  return strg

s = input("Enter a string: ")
print (StrRev(s))
Enter fullscreen mode Exit fullscreen mode

4

Using Recursive function

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

s = input("Enter a string: ")
print(StrRev(s))
Enter fullscreen mode Exit fullscreen mode

5

Using Stack Operations

def StackCreate():
    stack=[]
    return stack


def isEmpty(stack):
    if len(stack) == 0:
        return true


def push(stack,item):
    stack.append(item)

def pop(stack):
    if isEmpty(stack): return
    return stack.pop()


def StrRev(string):
    n = len(string)


    stack = StackCreate()

    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 = input("Enter a string: ")
print (StrRev(s))

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Let's Get Hacking

Join the DEV x MongoDB Atlas Hackathon 2022 and use your ingenuity and creativity to build an application using MongoDB's cloud based developer data platform, MongoDB Atlas.

Join the Hackathon