You are currently viewing How to Reverse a String in Python

How to Reverse a String in Python

Programmers have a variety of choices when it comes to reversing strings in Python. With some practice and creativity, it’s easy to come up with unique solutions for reversing strings by using different combinations of these methods. In this blog, we will see two methods to reverse a string in python i.e.;

Programmers have a variety of choices when it comes to reversing strings in Python. With some practice and creativity, it’s easy to come up with unique solutions for reversing strings by using different combinations of these methods. In this blog, we will see two methods to reverse a string in python i.e.;

  1. Slice operator (`[::-1]`)
  2. Built-in method `reversed`

Method 1: Reverse a String using Slicing

You can reverse a string in python using slicing. Slicing is when you take a part of a string and create a new string from it. To reverse a string using slicing, you need to specify the start, stop, and step. The start is where you want to start reversing the string from and the stop is where you want to stop. The step is how many characters you want to take at a time. To reverse complete string we use [::-1].

Code:

str = "AiOcta.com"
rev_str = str[::-1]
print(rev_str)

Output:

moc.atcOiA

Method 2: Reverse a String using Reversed Function

In Python, the reversed() function is used to reverse iterators. The syntax of the reversed() function is: reversed(seq). Here, seq must be an object that supports the sequence protocol (an iterator). If the given object doesn’t support the sequence protocol, TypeError will be raised. We use string object in this function to reverse it.

Code:

str = 'AiOcta.com'
rev_str = ''.join(reversed(str))
print(rev_str)

Output:

moc.atcOiA

References:

https://docs.python.org/3/

Leave a Reply