What is the meaning of “int(a[::-1])” in Python?

Total
0
Shares

I cannot understand this. I have seen this in people’s code. But cannot figure out what it does. This is in Python.

str(int(a[::-1]))

Solution

Assuming a is a string. The Slice notation in python has the syntax –

list[<start>:<stop>:<step>]

So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.

Example –

>>> a = '1234'
>>> a[::-1]
'4321'

Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *