There are different ways to reverse a string in Python.
The usual way to reverse a string is to use slicing with a negative step
:
>>> string = "hello world"
>>> string[::-1]
'dlrow olleh'
Breaking it down, string[:]
means: "take the string from beginning to end",
and string[::-1]
means that the string should be taken one step at a time,
adding -1
to the index after each step.
The final result is that the string gets reversed.
If you don't understand precisely what's going on, don't worry too much about
it. Just put [::-1]
after your string (or list, or tuple) to reverse it.
There is a built-in function named reversed
that can give you an iterator
over the string that runs in reverse. For example:
>>> string = "abc"
>>> for letter in reversed(string):
... print(letter)
...
c
b
a
However you cannot print this iterator directly, or you will see the
reversed
object:
>>> print(reversed("abc"))
<reversed object at 0x7f8222e12210>
You can write your own function to reverse a string:
def reverse(string):
result = ""
index = len(string) - 1
while index >= 0:
result += string[index]
index -= 1
return result
print(reverse("hello"))
Running the code correctly prints olleh
.