如何在Python中检查回文?

Geo*_*tin 1 python

嗨,我正在isPalindrome(x)为三位数的整数工作python函数,如果百位数等于1位数则返回True,否则返回false.我知道我必须在这里使用字符串,这就是我所拥有的:

def isPal(x):
    if str(1) == str(3):
        return "True"

    else:
        return "False"
Run Code Online (Sandbox Code Playgroud)

的str(0)是单位的地方,str(2)是百位.我得到的只是假的?谢谢!

jam*_*lak 6

数组访问完成[],而不是().此外,如果您正在寻找数百个和单位,请记住数组是0索引,这是代码的缩短版本.

def is_pal(num):
    return num[0] == num[2]

>>> is_pal('123')
False
>>> is_pal('323')
True
Run Code Online (Sandbox Code Playgroud)

您可能希望将数字作为参数接收,然后将其转换为字符串:

def is_pal(num):
    x = str(num)
    return x[0] == x[2]
Run Code Online (Sandbox Code Playgroud)

请注意,您只需检查字符串是否等于它的反向,它适用于任意数量的数字:

>>> x = '12321'
>>> x == x[::-1]
True
Run Code Online (Sandbox Code Playgroud)