How to reverse strings in Python
- Previous Page Remove Duplicates from List
- Next Page Python Example
Learn how to reverse strings in Python.
There is no built-in function to reverse strings in Python.
The fastest (and also the simplest?) method is to use backward stepping slices,-1
.
Example
Reverse the string "Hello World":
txt = "Hello World"[::-1] print(txt)
Example Explanation
We have a string, "Hello World", and we want to reverse it:
The string to be reversed
txt = "Hello World" [::-1] print(txt)
Create a slice starting from the end of the string and then move backward.
In this particular example, the slice statement [::-1]
is equivalent to [11:0:-1]
, which means starting from position 11 (because "Hello "World" has 11 characters), ending at position 0, moving with a step size -1
, negative one means one step backward.
Cut String
txt = "Hello World" [::-1] print(txt)
Now we have a reversed string "Hello World" txt
.
Print String to Demonstrate Result
Print List
txt = "Hello World"[::-1] print(txt)
Create Function
If you want a function that can send a string and return it backwards, you can create a function and insert the code in the above example
Example
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
Example Explanation
Create a function with string as parameter.
Create Function
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
Cut the string from the end and move backward.
Cut String
def my_function(x): return x [::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
Return the reversed string.
Return String
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt )
Call Function Using String as Parameter:
Call Function
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
Print Result:
Print Result
def my_function(x): return x[::-1] mytxt = my_function("I wonder how this text looks like backwards") print(mytxt)
- Previous Page Remove Duplicates from List
- Next Page Python Example