Saturday, 21 July 2018

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




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]))


Answer



Assumming a is a string. The Slice notation in python has the syntax -



list[::]


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 = '1232'
>>> a[::-1]
'2321'


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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...