The code below determines if c
is a palindrome. I was just wondering how int(str(c)[::-1]) == c
works, as I am new to Python and have not been able to find any information on this.
def is_pal(c):
return int(str(c)[::-1]) == c
The code below determines if c
is a palindrome. I was just wondering how int(str(c)[::-1]) == c
works, as I am new to Python and have not been able to find any information on this.
def is_pal(c):
return int(str(c)[::-1]) == c
The [::-1]
is in the form of the [start:end:step]
syntax. When you don't specify the start and end, it works with the whole string. When you specify step as -1
, it reverses the string and compares whether the reversed string is the same as the original.
>>> s = 'hello'
>>> s[1:4]
ell
>>> s[:]
hello
>>> s[::2]
hlo
>>> s[::-1]
olleh
>>> s = 'racecar'
>>> s[::-1]
'racecar'
>>> s == s[::-1]
True
You can rewrite your program like this.
def is_pal(c):
A = str(c) #Python builtin "str" function
B = A[::-1] #Python "slice"
C = int(B) #Python builtin "int" function
D = C == c #Python "==" operator
return D