• Register

In this article, I am going to explain two ways to invert a string in Python.

Table of contents:

  • Invert string in Python with slices.
  • Invert string in Python manually.
  • Putting it all together.
The first way to invert a string is by using slicing operations in Python, and the second is the “manual” way using a loop and creating a new string; analyzing the algorithm further.

Invert string in Python with slices:

Let's first look at the short and easy way that an algorithm created by us does not use. Is the next:

def  invert_string ( string ):
    return  string [:: - 1 ]

It is to "cut" the chain but without specifying start or end, only specifying the step ; in this way we advance from -1in -1reversing the string .

A little difficult to understand but it works. Use this method if you want to invert the chain in the most optimal way.

Invert string in Python manually:

Now let's look at the manual approach where the code can be applied to other programming languages ​​(if your teacher gave you a function to invert a string in Python this is exactly what you are looking for).

The algorithm for inverting a string in Python is simple:

We create a new empty string. Then we go through the original chain letter by letter, and we add the letter to the chain created at the beginning (respecting its content). In the end, we return the chain created initially.

The code is the following:

def  invert_manual_string ( string ):
    inverted_string  =  ""
    for  letter  in  string :
        inverted_string  =  letter  +  inverted_string
    return  inverted_string

The important part when inverted_string we assign the value of letter + inverted_string; in this way, we add the letter to the beginning.

Putting it all together:

If you want to try the two ways to invert a string you can use the following code:

def invert_string (string):
     return string [:: - 1]


def invert_manual_string (string):
     inverted_string = ""
     for letter in string:
         inverted_string = letter + inverted_string
     return inverted_string


print (invert_string ("Hello"))
print (invert_manual_string ("Hello"))
print (invert_string ("kodlogs.me"))
print (invert_manual_string ("kodlogs.me"))
print (invert_string ("All the young dudes"))
print (invert_manual_string ("All the young dudes"))

 

37,480 points
11 5 4