5 Best Ways for Python Reverse String with Examples

5 Best Ways for Python Reverse String with Examples

Share:

Introduction

Python Reverse String is an important function when you are working with strings. Oftentimes you need to reverse a string and this tutorial will teach you how to do it. Python has a few modules and tools to help us build reversed copies of the strings efficiently and quickly. Knowing about these modules and functions for Python reverse string will help you improve your programming skills. In this tutorial, we will learn five essential ways for Python Reverse String with examples. Let’s get started.

How To Reverse A String with Python

Python reverse string can be a necessity when you want to work with strings in reverse order. However, there is no built-in Python reverse function to do that. That’s why knowing other methods to reverse strings can be useful. 

Some of the popular ways to reverse a string in Python are-

  • – Slicing
  • – Join() and Reversed() function
  • – Loops
  • – Reverse() List function

Among them, two methods are very important for reversing strings – Slicing and Reversed() functions. Strings are sequence data types which means they are indexable, iterable, and sliceable. The slicing method allows you to directly generate a reversed copy of the given string.

The reversed() function doesn’t work well with the string, as we said before. Because Strings have fixed values in Python, they are immutable; hence, a Python reverse string in place is not possible. To achieve that, we need to create a reversed copy of the string by using the reversed() function to create an iterator. More about it later. Let’s now start with the first method for Python reverse string.

Related Post: 8 Best Methods To Use Python Filter List.

How To Reverse A String In Python Using Slicing?

Slicing is the fastest and most efficient technique for python reverse string. It uses a slice that takes a backward step: -1. It allows the coder to extract items from the particular sequence using offsets. Offsets are different combinations of numeral indices. 

The first offset defines the starting point, the second is the ending point, and the third one indexes the value you want to jump in each iteration. The value starts from 0 and ends at one less than the original string length. 

The syntax looks like this:

a_string[start:stop:step]

Python String Slicing Example-

Let’s say we have a string, “ABCDE”, which we want to reverse:

String = "ABCDE"
for char in String[::-1]:
print(char)

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

s = "ABCDE"

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

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

Output

The original string is : ABCDE

The reversed string is : EDCBA

That’s how Python reverse string works with Slicing. This method is fairly easy and fast. But how to reverse a string in python without slicing? Well, there are other methods to reverse string programs in Python. Let’s see them one by one.

Related Post: Python Install Mac Tutorial

Reverse a String Using Join() and Reversed()

The easiest and readable method to iterate a string in reverse order is to use reversed() function. The reverse() method updates the list without taking arguments and also does not return value. You can use it along with join() to create reversed strings.

However, the main use case of reversed() is to support reverse iteration on Python iterables. With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.

With For Loop

Here’s how you can iterate over a string in reverse order with reversed():

string= "ABCDE"

for char in reversed(string):

  print(char)

Output:

EDCBE

The for-loop in this example is very readable. The name of reversed() clearly expresses its intent and communicates that the function doesn’t produce any side effects on the input data. Since reversed() returns an iterator, the loop is also efficient regarding memory usage.

With Join()

The Python reverse function: reversed() is applied on the given string which returns a reversed iterator. The iterator’s elements will be joined to an empty string. Join() function will separate that empty string, and a reversed string is formed. 

# Python code to reverse a string

# using reversed()

# Function to reverse a string

def reverse(string):

    string = "".join(reversed(string))

    return string

s = "ABCDE"

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

print(s)

print("The reversed string(using reversed) is : ", end="")

print(reverse(s))

Output:

The original string is : ABCDE

The reversed string(using reversed) is : EDCBA

Python Reverse List Function

Python reverse list function: list.reverse() is a handy tool to reverse a Python list in place.

But we want to reverse strings that are immutable as I said before. Python reverse string in place cannot happen with the same method. 

What’s the solution? You can create a string subclass with the reverse() function that will mimic list.reverse(). 

Syntax for Python reverse list function is:

list.reverse()

Python Reverse List Example

# Operating System List

systems = ['Windows', 'macOS', 'Linux']

print('Original List:', systems)

# List Reverse

systems.reverse()

# updated list

print('Updated List:', systems)

Output

Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']

Reverse a Sentence in Python

Let’s say you want to reverse a sentence in Python. To achieve that, we break the sentence into a string of words and reverse them.
To reverse words in a string Python, you need to:

  1. Take a string as input.
  2. Convert the sentence into a list of words.
  3. Join the list in the reverse order which ultimately is the reversed sentence.

Python Reverse String Sentence Example:

We give an Input:
Input : str =
“OPTYMIZE HIRE TOP 3% DEVELOPERS”

And expect:
Output : str =
 “DEVELOPERS 3% TOP HIRE OPTYMIZE”

Related Post: How to Represent Python Infinity in Simple Ways?

Reverse Words in The Given String Python Program

# Python code
# To reverse words in a given string

# input string
string = "OPTYMIZE HIRE TOP 3% DEVELOPERS"
# reversing words in a given string
s = string.split()[::-1]
l = []
for i in s:
# apending reversed words to l
l.append(i)
# printing reverse words
print(" ".join(l))

Output

DEVELOPERS 3% TOP HIRE OPTYMIZE

Conclusion

Making a Reverse string program in Python can prove useful for a variety of operations. Python provides a range of tools and modules to help you perform Python reverse string functions quickly and efficiently. In this tutorial, we learned some important ways to reverse string in Python and we can use them to our advantage in string processing challenges.

0

Share:

Subscribe for newsletter

Trusted By

Our platform focuses on making the remote hiring process easier by providing top quality vetted developers from around the world. Through our service many well-known companies have scaled their product development team.

Related Article

Ready to scale your team with remote engineers?