-2

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
tshepang
  • 12,111
  • 21
  • 91
  • 136
Jojo
  • 1,117
  • 2
  • 15
  • 28
  • 2
    What part of it don't you understand? Have you tried out the various bits of it in a Python interpreter prompt? The `[::-1]` is slice notation; it slices from start to end and uses a negative step to produce a *reversed* copy; that part is a duplicate though. – Martijn Pieters May 02 '14 at 11:58
  • Your function doesn't work: is_pal("aabbaa") => ValueError: invalid literal for int() with base 10: 'aabbaa' Because of the extra int(). Why do you need to convert it to int ? – Grapsus May 02 '14 at 12:01
  • That's the canonical post, [this search](http://stackoverflow.com/search?q=%22%5B%3A%3A-1%5D%22+%5Bpython%5D+is%3Aq) lists the many duplicates. – Martijn Pieters May 02 '14 at 12:01
  • @Grapsus: it works just fine for *integers*. `is_pal(12321)` returns `True`. – Martijn Pieters May 02 '14 at 12:01
  • Ok, my bad. Who calls an integer c ?! – Grapsus May 02 '14 at 12:02
  • minimal search in web would resolve ur doubt.Duplication never earn u reputation – sundar nataraj May 02 '14 at 12:03

2 Answers2

1

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.

Examples

>>> s = 'hello'
>>> s[1:4]
ell
>>> s[:]
hello
>>> s[::2]
hlo
>>> s[::-1]
olleh

>>> s = 'racecar'
>>> s[::-1]
'racecar'
>>> s == s[::-1]
True
Community
  • 1
  • 1
sshashank124
  • 31,495
  • 9
  • 67
  • 76
0

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
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43