Python string doesn’t support reverse function so we must use a slice that steps backward. That is extra the slice statement [::-1].
This is the fastest way to do that. Below is the guide on how to reverse a string in Python as we go through below.
We have a string “Hello World” and we will reverse it by the following command:
str ="Hello World" [::-1] print(str)
We must use the slice statement [::-1] because it will start at the end of the string until the beginning of the string. -1 means one step backward.
The slice statement [::-1] will directly impact the str variable, so that the above string will be reversed.
Let’s try writing your own command and extra the slice statement [::-1]. Output to see the result.
Create a function
If you want to send your strings into a function and return them backward:
def string(x): return x [::-1] myback = string("Hello World") print(myback)
The slice statement [::-1]
Return the backward string
Call the function and replace variable x with a string
Let’s try writing your own command. Output to see the result.
You have just seen detailed instructions on how to reverse a string in Python.
Thank you for reading.
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications including CCNA RS, SCP, and ACE. As an IT engineer and technical author, he writes for various websites.