×


Reverse a String in Python - How to do it ?

Python string doesn't support reverse function so we must use a slice that steps backward. That is extra the slice statement [::-1]. In fact, In Python, strings are ordered sequences of character data.

Generally, There is no built-in function to reverse a String in Python.

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Python strings queries.

In this context, we shall look into a complete guide on how to reverse a string in Python.


For Example

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

str ="Hello World" [::-1]
print(str)

The output will look like this:

dlroW olleH


What does this imply ?

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].


How to 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 output will take the following look:

dlroW olleH


What does this mean ?

The slice statement [::-1]

Call the function and replace variable x with a string


[Need to fix Phyton packages issues ? We are here to help.]


Conclusion

This article covers the procedure on how to reverse a string in Python. Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0.

To reverse a string using slicing, write:

$ stringname[stringlength::-1] # method 1 

Or write without specifying the length of the string:

$ stringname[::-1] # method2

The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).