Question

I was looking for a way to print a string backwards, and after a quick search on google, I found this method:

Suppose a is a string variable. This will return the a string backwards:

a[::-1]

Can anyone explain how that works?

Was it helpful?

Solution

Sure, the [::] is the extended slice operator. It allows you to take substrings. Basically, it works by specifying which elements you want as [begin:end:step], and it works for all sequences. Two neat things about it:

  • You can omit one or more of the elements and it does "the right thing"
  • Negative numbers for begin, end, and step have meaning

For begin and end, if you give a negative number, it means to count from the end of the sequence. For instance, if I have a list:

l = [1,2,3]

Then l[-1] is 3, l[-2] is 2, and l[-3] is 1.

For the step argument, a negative number means to work backwards through the sequence. So for a list::

l = [1,2,3,4,5,6,7,8,9,10]

You could write l[::-1] which basically means to use a step size of -1 while reading through the list. Python will "do the right thing" when filling in the start and stop so it iterates through the list backwards and gives you [10,9,8,7,6,5,4,3,2,1].

I've given the examples with lists, but strings are just another sequence and work the same way. So a[::-1] means to build a string by joining the characters you get by walking backwards through the string.

OTHER TIPS

The "-1" part represents the "step" part of the slicing—in this case, it goes through the string 1 character at a time, but backwards (a negative step means start from the end of the string). If you specify the step to be 2, for instance, you would get every other character of the string, starting with the first one. If you specify a step of -2, then you'd get every other character of the string, starting with the last character and working backwards.

So, in a nutshell, if a = '12345':

  • a[::2] becomes 135
  • a[::-1] becomes 54321
  • a[::-2] becomes 531

I think the following makes a bit more sense for print strings in reverse, but maybe that's just me:

for char in reversed( myString ):  
  print( char, end = "" )

It's the extended slice notation:

sequence[start:end:step]

In this case, step -1 means backwards, and omitting the start and end means you want the whole string.

It's called Slice Notation in Python and you can read a bit more of how it works here:

Explain Python's slice notation

It's using extended slicing - a string is a sequence in Python, and shares some methods with other sequences (namely lists and tuples). There are three parts to slicing - start, stop and step. All of them have default values - start defaults to 0, stop defaults to len(sequence), and step defaults to 1. By specifying [::-1] you're saying "all the elements in sequence a, starting from the beginning, to the end going backward one at a time.

This feature was introduced in Python 2.3.5, and you can read more in the What's New docs.

[::-1] gives a slice of the string a. the full syntax is a[begin:end:step] which gives a[begin], a[begin+step], ... a[end-1]. WHen step is negative, you start at end and move to begin.

Finally, begin defaults to the beginning of the sequence, end to the end, and step to -1.

I would do it like this:

variable = "string"
message = ""
for b in variable:
    message = b+message
print (message)

and it prints: gnirts

a string is essentially a sequence of characters and so the slicing operation works on it. What you are doing is in fact:

-> get an slice of 'a' from start to end in steps of 1 backward.

It's basic step notation, consider the functionality of:

a[2:4:2]

What happens is the index is sliced between position 2 and 4, what the third variable does is it sets the step size starting from the first value. In this case it would return a[2], since a[4] is an upper bounds only two values are return and no second step takes place. The (-) minus operator simply reverses the step output.

Consider the list below

l=[12,23,345,456,67,7,945,467]

Another trick for reversing a list may be :

l[len(l):-len(l)-1:-1] [467, 945, 7, 67, 456, 345, 23, 12]

l[:-len(l)-1:-1] [467, 945, 7, 67, 456, 345, 23, 12]

l[len(l)::-1] [467, 945, 7, 67, 456, 345, 23, 12]

we can use append and pop to do it

def rev(s):
    i = list(s)
    o = list()
    while len(i) > 0:
        o.append(t.pop())

    return ''.join(o)

Without using reversed or [::-1], here is a simple version based on recursion i would consider to be the most readable:

def reverse(s):

  if len(s)==2:
    return s[-1] + s[0]

  if len(s)==1:
    return s[0]

  return s[-1] + reverse(s[1:len(s)-1]) + s[0]

Using extended slice syntax

word = input ("Type a word which you want to reverse: ")
def reverse(word):
  word = word[::-1]
  return word
print (reverse(word))

You can use reversed() function. For example

x = "abcd"
for i in reversed(x):
        print(i, end="")
print("\n")
L = [1,2,3]
for i in reversed(L):
        print(i, end="")

prints dcba and 321

the first two bounds default to 0 and the length of the sequence, as before, and a stride of −1 indicates that the slice should go from right to left instead of the usual left to right. The effect, therefore, is to reverse the sequence.

name="ravi"
print(name[::-1]) #ivar
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top