Python program to reverse a string

In this concept, we have 8 different ways to reverse a string using python. Most commonly used methods are explained below:

  • Using the slicing method
  • Using the reversed() function
  • Using For loop
  • Using the Recursion
  • Using join() and list comprehension method
  • Using the reduce() function
  • Using the stack
  • Using the list comprehension
  • Using the while loop

Reversing a string using slicing method

The best way to reverse a string using string indexing, with a step of -1.

def reverse_string(s):
    return s[::-1]
print("Reverse of the string is : ", reverse_string("Python")
Output : nohtyP

Reversing a string using For loop

Here we use For loop to iterate over the characters in the string and build a new string by adding each character to the beginning of an empty string

text = 'Codespeedy'
reversed_string = ''

for character in text:
    reversed_string = character + reversed_string

print(reversed_string)

Output: ydeepsedoC

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top