HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Learn how to reverse a String in Python
We have a string, "Hello World", which we want to reverse:
txt = "Hello World"[::-1]
print(txt)
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.
txt = "Hello World"[::-1]
print(txt)
Now we have a string txt
that reads "Hello
World" backwards.
Print the String to demonstrate the result
txt = "Hello World"[::-1]
print(txt)
If you like to have a function where you can send your strings, and return them backwards, you can create a function and insert the code from the example above.
def my_function(x):
return x[::-1]
mytxt =
my_function("I wonder how this text looks like backwards")
print(mytxt)
Create a function that takes a String as an argument.
def my_function(x):
return x[::-1]
mytxt =
my_function("I wonder how this text looks like backwards")
print(mytxt)
Slice the string starting at the end of the string and move backwards.
def my_function(x):
return x[::-1]
mytxt =
my_function("I wonder how this text looks like backwards")
print(mytxt)
Return the backward String
def my_function(x):
return
x[::-1]
mytxt =
my_function("I wonder how this text looks like backwards")
print(mytxt )
Call the function, with a string as a parameter:
def my_function(x):
return
x[::-1]
mytxt = my_function("I
wonder how this text looks like backwards")
print(mytxt)
Print the result:
def my_function(x):
return
x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)