python如何判断回文

316次阅读
没有评论

python如何判断回文

打开JUPTER NOTEBOOK,新建一个PYTHON文档。

python如何判断回文

n = input("Please input string: ")
print(n)

我们首先让用户输入要进行判断的字符串,然后打印出来查看一下。

python如何判断回文

n = input("Please input string: ")
is_palidrome = n[::-1]
if n == is_palidrome:
    print("This is a palidrome.")
else:
    print("This is not a palidrome.")

我们可以用IF语句来进行判断,判断倒向的是否等于正向的即可。

python如何判断回文

n = input("Please input string: ")
if n == n[::-1]:
    print("This is a palidrome.")
else:
    print("This is not a palidrome.")

其实可以简化一下流程。

python如何判断回文

def reverse(n):
    a = ""
    for i in n[::-1]:
        a = a + i
        
    return a
n = input("Please input string: ")
a = reverse(n)
if n == a:
    print("This is a palidrome.")
else:
    print("This is not a palidrome.")

也可以定义一个新的FUNCTION,然后进行判断。

python如何判断回文

def reverse(n):
    a = ""
    for i in range(len(n)):
        a = a + n[len(n)-1-i]
        
    return a
n = input("Please input string: ")
a = reverse(n)
if n == a:
    print("This is a palidrome.")
else:
    print("This is not a palidrome.")

我们可以利用长度范围不断往回减去范围值,得到反向的字符串。

python如何判断回文

def reverse(n):
    a = ""
    for i in range(len(n)):
        a = a + n[len(n)-1-i]
        
    return a
n = input("Please input string: ")
a = reverse(n)
if n == a:
    print("This is a palidrome.")
else:
    print("This is not a palidrome.")

继续做多种输入来进行判断。

python如何判断回文

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-24发表,共计1171字。
新手QQ群:570568346,欢迎进群讨论 Python51学习