How To Reverse A String in Python
How To Reverse A String in Python
❮ PreviousNext ❯
The fastest (and easiest?) way is to use a slice that steps backwards, -1.
Example
Reverse the string "Hello World":
Example Explained
We have a string, "Hello World", which we want to reverse:
Create a slice that starts at the end of the string, and moves backwards.
In this particular example, the slice statement [::-1] means start at the end of the
string and end at position 0, move with the step -1, negative one, which means one step
backwards.
Example
def my_function(x):
return x[::-1]
print(mytxt)
Try it Yourself »
Example Explained
Create a function that takes a String as an argument.
Create a Function
def my_function(x):
return x[::-1]
print(mytxt)
Slice the string starting at the end of the string and move backwards.
print(mytxt)
print(mytxt )
Call the function, with a string as a parameter:
print(mytxt)
print(mytxt)