Scripting

How to Reverse a String in Python

How-to-Reverse-a-String-in-Python

Introduction

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.

Example

We have a string “Hello World” and we will reverse it by the following command:

str ="Hello World" [::-1]

print(str)

Output:

dlroW olleH

Explained

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)

Output:

dlroW olleH

Explained

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.

Conclusion

You have just seen detailed instructions on how to reverse a string in Python.

Thank you for reading.

Similar Posts