Python Examples

Python Program - Reverse a given String



In Python, the reverse of a given string can be found out by using below mentioned methods.

Method 1: Using iteration

In the example below, the string called MyString is reversed using ReverseString() method. A variable last is created which points to the last character of the string. An empty string revString is created. By using a for loop and iterating from last to 0, characters from MyString is placed in revMystring in reverse order.

def ReverseString(MyString):
  last = len(MyString) - 1

  revString = ""
  for i in range(last, -1, -1):
    revString = revString + MyString[i]
  print(revString)

ReverseString("Hello World")
ReverseString("Programming is fun")
ReverseString("Reverse this string")

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 2: Using Recursion

The above result can also be achieved using recursive function:

def ReverseString(MyString):
  if len(MyString) == 0:
    return

  temp = MyString[0]
  ReverseString(MyString[1:])
  print(temp, end="")

ReverseString("Hello World")
print()
ReverseString("Programming is fun")
print()
ReverseString("Reverse this string")
print()

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 3: Printing the string in reverse order

The same can be achieved by printing the string in reverse order. Consider the example below:

def ReverseString(MyString):
  last = len(MyString) - 1

  for i in range(last, -1, -1):
    print(MyString[i], end="")
  print()

ReverseString("Hello World")
ReverseString("Programming is fun")
ReverseString("Reverse this string")

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 4: Reverse the String in another way

In the example below, the string is reversed using [ : : -1] slicing method.

def ReverseString(MyString):
  print(MyString[::-1])

ReverseString("Hello World")
ReverseString("Programming is fun")
ReverseString("Reverse this string")

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 5: Using built-in functions

In the example below, the string is reversed using Python built-in functions reversed() and join().

def ReverseString(MyString):
  revString = "".join(reversed(MyString))
  print(revString)

ReverseString("Hello World")
ReverseString("Programming is fun")
ReverseString("Reverse this string")

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR




5