Python案例:四种方法判断回文字符串

一、回文字符串

1、概念

回文字符串是一个正读和反读都一样的字符串。

2、实例

  • “abcdedcba”
  • “天长地久地长天”

二、判断回文字符串

1、创建程序 - 回文字符串判断.py

在这里插入图片描述

# -*- coding: utf-8 -*-
"""
Created on Sun Oct  4 19:01:00 2020

@author: howard

判断一个字符串是否回文字符串
"""

def isParlindromic01(str):
    for i in range(len(str) // 2):
        if str[i] != str[-i - 1]:
            return False
    return True

def isParlindromic02(str):
    ls = list(str)
    ls.reverse()
    return str == ''.join(ls)

def isParlindromic03(str):
    return str == ''.join(reversed(str))

def isParlindromic04(str):
    return str == str[::-1]

str = input('输入字符串:')

print('方法一:', end='')
if isParlindromic01(str):
    print('{}是回文字符串。'.format(str))
else:
    print('{}不是回文字符串。'.format(str))
    
print('方法二:', end='')
if isParlindromic02(str):
    print('{}是回文字符串。'.format(str))
else:
    print('{}不是回文字符串。'.format(str))
    
print('方法三:', end='')
if isParlindromic03(str):
    print('{}是回文字符串。'.format(str))
else:
    print('{}不是回文字符串。'.format(str))
    
print('方法四:', end='')
if isParlindromic04(str):
    print('{}是回文字符串。'.format(str))
else:
    print('{}不是回文字符串。'.format(str))

2、运行程序,查看结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/howard2005/article/details/108921500