Knowledge for the World

Print a string in reverse in Python

The solution is simple using the extended slice operator. "some string"[::-1] will print the string in reverse resulting in "gnirts emos" . This guide provides an explanation of how this works. Keep in in mind that strings are a list of characters so the extended slice operator works to reverse a list as well.

1

Assuming we have the following string:

x = "hello world"

we can reverse it like this:

x[::-1]

resulting in:

"dlrow olleh"

2

The extended slice specifies a beginning, end, and step. Beginning is the place to begin in the sequence. End is the place to stop in the sequence. This allows you to slice off a portion of a sequence.

For the string

x = "hello world"

We can get the 2 - 5 characters like this:

x[2:5]

Notice that this starts after the second character as the index starts at 0, and it ends after the fifth character producing:

"llo"

To match our example, leaving the beggining and end values empty means that we start at the beginning of the sequence and end at the end. Basically it includes the entire sequence.

"hello world"[::]

produces

"hello world"

Step refers to how we will step through the sequence. If step is -1 then we are stepping through the sequence in reverse hitting every element. If step is 5, then we are moving through the sequence hitting every fifth element.

So using this:

"hello world"[::-1]

means that we include the entire string and step through backwards ultimately reversing the string.