How to reverse a String in Python

How to reverse a String in Python

Learn two methods and find out which is fastest Reverse a String in Python

How To Reverse a String in Python. Learn two methods and find out which is fastest

A string is a sequence of character data. We commonly refer to it as text data. Additionally, strings are iterables, which are enumerables—a data type that can be counted over—that have a structured order as well. Reversing a string means taking the last character and making it the first, second to last becomes second, etc.

Here’s a quick visual example:

name = "Jonathan"

# name in reverse => "nahtanoJ"

So, how do we reverse a string? There are two ways that I’ll cover.

  • Programmatically using reverse/join. This is a generic technique that involves creating a reversed iterable and reconstituting it as a string. The exact implementation is Python-specific; however, the technique is broadly implemented across many languages.
  • The Pythonic way using slice notation. This is a condensed technique that is more specific to Python as slice notation is not found in all languages.

Technique 1. Reverse/Join

This method involves treating the string as an array of characters, reversing it, and reconstituting it as a string. In other languages, this technique might involve a for loop to iterate over each index and create a reversed data set. The next step is to take the array and recombine it as a string.

Here’s a JavaScript example to show how this looks within a traditional for loop.

var name = "Jonathan";
var arr = [];

for(var i=name.length-1; i >= 0; i--) {

var flipped = arr.join("");

console.log(flipped); // nahtanoJ

What we do here is begin at the highest index and manually count down, populating an array with each character. Finally, we join the array with an empty string as a delimiter, meaning the characters are sequential with nothing between them.

In Python, we don’t have traditional for loops. It could be recreated using a while loop, but we’re not going to go that route. Instead, we’ll use the reversed() function to return a reverse iterator that will be similarly joined by empty strings.

name = "Jonathan"

reversed = "".join(reversed(name))

print(reversed) # nahtanoJ

Notice that .join() is a member of the string class in the Python implementation.

Technique 2. Slice Notation

Slice notation is a technique unique to Python that allows a shorthand notation within an iterable’s square brackets, which then executes a traditional slice.

Slice notation involves two colons and up to three values within the square brackets. The first, middle, and end values—separated by colons—are as follows: [start:stop:step]

By omitting the start and stop positions while passing -1 as the step value, we instruct Python to slice counting backwards and not to stop before the end of the string.

name = "Jonathan"

print(name[::-1]) # nahtanoJ

Performance Comparison

According to Dan Bader, slice notation is up to seven times faster than the reverse/join technique!

I replicated his test scenarios and yielded similar, but not as dramatic results.

import timeit

def reverse_join(s):
    return "".join(reversed(s))

def slice_notation(s):
    return s[::-1]

s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

reverse_join_times = timeit.repeat(lambda: reverse_join(s))
slice_notation_times = timeit.repeat(lambda: slice_notation(s))

avg_reverse = sum(reverse_join_times)/len(reverse_join_times)
avg_slice = sum(slice_notation_times)/len(slice_notation_times)

print(avg_reverse) # 1.8536329854000002 
print(avg_slice) # 0.38605856120000015
print(avg_reverse / avg_slice) # 4.801429554206191

Do you have another way of reversing a string? Share it and any other thoughts or insights in the comments below!

Thank you for reading !

Python Data Science Development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[]( "")**, our full-stack Python development services...

Hire Python Developers India

Looking to build robust, scalable, and dynamic responsive websites and applications in Python? At **[]( "")**, we constantly endeavor to give you exactly what you need. If you need to...

Data Science With Python | Python For Data Science | Data Science For Beginners

This Data Science with Python Tutorial will help you understand what is Data Science, basics of Python for data analysis, why learn Python, how to install Python, Python libraries for data analysis, exploratory analysis using Pandas, introduction to series and dataframe, loan prediction problem, data wrangling using Pandas, building a predictive model using Scikit-Learn and implementing logistic regression model using Python.

50 Data Science Jobs That Opened Just Last Week

Data Science and Analytics market evolves to adapt to the constantly changing economic and business environments. Our latest survey report suggests that as the overall Data Science and Analytics market evolves to adapt to the constantly changing economic and business environments, data scientists and AI practitioners should be aware of the skills and tools that the broader community is working on. A good grip in these skills will further help data science enthusiasts to get the best jobs that various industries in their data science functions are offering.