How to Reverse a String in Python

This site contains affiliate links to products. We may receive a commission for purchases made through these links.

As a high-level, general-purpose programming language, Python is an indispensable tool for web and software developers, data analysts, and other professionals. Whether you’re only starting to learn this language or already have some relevant coding experience, you may find performing certain tasks complicated.

In fact, many beginner programmers wonder how to reverse a string in Python. If you’re in the same position, we’ll explain different techniques to reverse your Python string without much effort.

Note: Syntax examples in this article are taken from Geeks for Geeks.

What Is Python?

Python is a general-purpose programming language for software and web development, data visualization, data analysis, and task automation. Python is utilized in most modern-day industries, and its developers are in high demand. Even people who work in non-IT-related fields like banking or financing use Python to be more productive.

The philosophy of Python is to emphasize the readability of code, ensuring it’s an object-oriented, structured, and functional language. Python has dynamic semantics and runs on a combination of dynamic binding and dynamic typing. For this reason, it’s especially popular for Rapid Application Development.

Programmers love using Python because of its productivity-related benefits. The edit-test-debug process is pretty simple, given the lack of a compilation step. If you’re a beginner who needs to debug a Python problem, you can do so easily. Entering the code wrong won’t cause the segmentation to fail. It raises an exception instead.

What Is a String in Python?

A Python string can be a collection of words or other characters. Strings are primitive data structures that are essential for data manipulation. With Python, you get a built-in string class called “str.”

All strings in Python are immutable. This means you can’t change them after creating them. To make string changes, you must create a new one. Developers who try to change the value of a string will receive an error.

We call strings sequences of Unicode, a system representing all characters from all languages. Every letter and character in a Unicode consists of a 4-byte number. Every number stands for a unique character.

Developers can represent a string by wrapping it within quotes. To do so, programmers use single, double, and triple quotes.

  • With single quotes, you can embed double quotes in the string.
  • With double quotes, you can embed single quotes in the string.
  • With triple quotes, you can use both double quotes and single quotes.

Given that strings are sequences of characters in Python, developers can access them through indexing and slicing, much like with tuples or lists. Every character in a string gets indexed with numbers starting from 0.

What Does Reversing a String in Python Mean?

String reversal is a common term in programming. As explained above, a string is a sequence of characters. When reversing a string, you completely flip the order of the characters. Basically, reversing a string means making it read backward.

The reverse order of strings may be required in numerous situations. What do you do if you have a string saying “ABCD” and you need to reverse it to “DCBA”?

Unfortunately, the Python programming language doesn’t have an in-built “reverse()” function in its String class. Given the immutability of strings, you can’t reverse them after placing them in order. Instead, you’ll have to make a reversed copy of the target string to complete the task.

How to Reverse a String in Python

To reverse a Python string, you have to use one of the following:

  • Slicing – creates the string’s reverse copy
  • Join() function – in combination with reversed() iterator
  • Creating a list and calling it the reverse() function
  • For loop – appends characters in their reverse order
  • While loop – iterates character strings in their reverse order and appends them
  • Recursion
  • Function call
  • List comprehension – creating a string’s element list in reverse order

If you’re new to Python and are looking for the easiest string reversal method, it’s recommended to go with slicing.

1. Reverse a String With Slicing

Slicing is the most common technique for reversing a script in Python. It lets you extract items from a sequence using different integer indices or offsets. The offsets define the following:

  • The first character in slicing’s index
  • The character that stops the slicing’s index
  • Value defining the number of characters you wish to jump through in every iteration

For Python string reversal using the slicing method, enter the code below:

“def reverse_slicing(s):

return s[::-1]

input_str = Hello world’

if __name__ == “__main__”:

print(‘Reverse String using slicing =’, reverse_slicing(input_str))”

If you were to enter the above script, you’d get this output:

“dlrow olleH”

2. Reverse a String With for Loop

For loop in Python is used for sequence iteration (strings, list, tuple, set, or dictionary). For isn’t like the “for” keyword used in other programming languages. It’s more of an iterator method you find in object-oriented languages.

Developers use the “for” loop to execute statement sets for each item in a tuple, list, set, and more.

For loops don’t require indexing variables to be set beforehand.

“def reverse_for_loop(s):

s1 = ”

for c in s:

s1 = c + s1 # appending chars in reverse order

return s1

input_str = ‘123456789’

if __name__ == “__main__”:

print(‘Reverse String using for loop =’, reverse_for_loop(input_str))”

The output for this script would be: Reverse String using for loop = 987654321

3. String Reversal With While Loop

While loops in Python iterate over a code block as long as the test condition or expression is true. Programmers use the while loop when they don’t know how many times to iterate beforehand.

While loops first check the test expression. The loop body is entered only if the expression turns out to be true. After an iteration, Python checks the expression again. The process continues until the expression turns out false.

You can determine the body of a while loop in Python using the indentation. The indentation marks the body, and the first line that isn’t indented marks the end.

All non-zero values are interpreted as true in Python. The language interprets “none” and “0” values as false.

Here’s how your syntax should look like if you want to reverse a string in Python using the while loop:

“def reverse_while_loop(s):

s1 = ”

length = len(s) – 1

while length >= 0:

s1 = s1 + s[length]

length = length – 1

return s1

input_str = 123456′

if __name__ == “__main__”:

print(‘Reverse String using while loop =’, reverse_while_loop(input_str))”

4. String Reversal With Join() and Reversed()

Reversing strings using the reversed() and str.join() functions is among the most popular ways of doing so in Python.

“def reverse_join_reversed_iter(s):

s1 = ”.join(reversed(s))

return s1”

5. Reverse a String With List reverse()

“def reverse_list(s):

temp_list = list(s)

temp_list.reverse()

return ”.join(temp_list)”

How to Reverse a String in Python

6. Reverse a String With Recursion

Recursion in Java is a special technique that makes it possible to break complex problems into simpler ones.

A code example for reversing a string in Python with Recursion looks like this:

“def reverse_recursion(s):

if len(s) == 0:

return s

else:

return reverse_recursion(s[1:]) + s[0]

s = “Hello World”

print(“The original string is: “, end=””)

print(s)

print(“The reversed string(using recursion) is: “, end=””)

print(reverse(s))”

The output for this line of code would be:

The original string is: Hello World

The reversed string(using recursion) is: dlroW olleH

7. String Reversal With List Comprehension()

List comprehension comes with a shorter syntax. It’s used when developers want to develop a new list with values already featured on an existing list. For example, if you’re working with a list of cities, you may want to create a new list that only contains cities that start with “B.”

Without list comprehension, you’d have to use a “for” statement and a conditional test. But thanks to list comprehension, you only have to use a single line of code.

With a list comprehension, you can also create an element list of the string in reverse order. Then, you should join the elements using the join() function. As a result, you get the reversed order string.

Here’s an example syntax for reversing a Python string using the comprehension list().

“# Function for string reversal

def reverse(string):

string = [string[i] for i in range(len(string)-1, -1, -1)]

return “”.join(string)

s = “123456”

print(“The original string is : “, s)

print(“The reversed string(using reversed) is : “, reverse(s))”

8. String Reversal With the Function Call

A callable object in Python can accept some parameters or arguments and return an object or a tuple with multiple objects. The smallest callable Python object is called a function.

The “function call” expression refers to passing the control and arguments (if existent) to a function in Python.

You can use the function call for Python string reversing by converting it to a list, then reversing it again and restoring it to a string.

Here’s what the syntax for such an algorithm would look like:

“# Function for string reversal

# by list-to-string conversion

# then reversing it and convert to string again

def reverse(string):

string = list(string)

string.reverse()

return “”.join(string)

s = “1234567890”

print(“The original string is : “, s)

print(“The reversed string(using reversed) is : “, reverse(s))”

The output for this line of code would be:

“The original string is: 1234567890

The reversed string(usingreversed) is: 0987654321”

Which Algorithm to Use for Python String Reversal?

As you can see, multiple algorithms can be used for string reversal in Python. But how do you decide which one is best for completing the reversal?

You can use the “timeit module” to run different iterations of the abovementioned functions. Then, you get the average time it takes to run these functions.

All the functions above are available in the “string_reverse.py” script, so you can execute them individually and see which is the fastest to run.

Online tests show that the slicing technique has the best execution time. All other functions are at least five times slower.

Reverse a String in Python Using Slicing

Python is a highly flexible programming language. You can achieve one task using multiple methods, and reversing a string is no different. But even though there are numerous ways to reverse strings in Python, the fastest and simplest method is slicing. The code for slicing is super simple, and you don’t need to write your logic for string reversal.

As you advance your Python skills, you may find that other techniques are more up your alley. Still, regardless of the complexity of the project you’re working on, stick with the techniques that will make your lines of code simpler and faster to execute.

Leave a Comment

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

Special offer for our visitors

Get your Free Coding Handbook

We will never send you spam. By signing up for this you agree with our privacy policy and to receive regular updates via email in regards to industry news and promotions