Python String Reverse

python-string-reverse-method-ipcisco

In python to print Python String Reverse, we can use slice function simply. To do this, we will use colon fort he starting index and fort he ending index. And we willl set the slice step as -1. The default slice step is 1. But here, we will do it as reverse direction, so we use -1.

 

You can also check python list reverse method to learn how to sort a list in reverse direction in python.

 

In the below Python String Reverse example, we will print the string from the reverse direction. Here, we will use two colon (:) and -1 as parameters.

 

character = "Aragorn"[::-1]
print(character)

 

The return of this python code will be the string that shows the reverese of the beginning string.

 

nrogarA

 

python-string-reverse-method-ipcisco

 

Here, we can change the last step parameter as -2 and we can print the string in reverse direction. But this time, we will print one character and we will not print the second one. We will print the third one but not the forth the one.

 

character = "Aragorn"[::-2]
print(character)

 

The output of this python string code will be like below:

 

noaA 

 

python-string-reverse-ipcisco

 

Let’s give another example for this reverse string example.

 

msg = "Hello Python"[::-1]
print(msg)

 

The output of this python code will be like below:

 

nohtyP olleH

 

 

msg = "Hello Python"[::-2]
print(msg)

 

The output of this python code will be like below:

 

nhy le

 

For different algorithms in different python codes, you can use Python String Reverse. The simplest way of doing this, is using string slicing with a step parameter -1. Instead of this way, there are also other alternative ways to write a python string in reverse direction.

 

For example we can use a loop with in function for Python String Reverse function. Here, we are defining a new function for our purpose. But this is the long way to print the reverse of a python string.

 

Back to: Python Programming Course > Python Strings

Leave a Reply

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

Contact

  • info@ipcisco.com
IPCisco is the Winner! “Best Certification Study Journey of 2019!”

Cisco-ITBlogAwards-2019-Winner-IPCisco-k

Python Programming Course