zoukankan      html  css  js  c++  java
  • type-of-python作业-判断字符串是否属于回文需要忽略其中的标点、空格与大小写

    type-of-python作业

    作业练习:要想检查文本是否属于回文需要忽略其中的标点、空格与大小写。例如,“Rise to vote, sir.”是一段回文文本,但是我们现有的程序不会这么认为。你可以改进上面的程序以使它能够识别

    这段回文吗?

    注:本文中用的python版本为3.70,编译器:PyCharm edu

    参考的网站网站一网站二网站三网站四:多谢前辈的指导!!!

    import string
    import re
    
    # 将字符串反转,并返回
    def reverse(text):
        return text[::-1]
    
    # 检测反转后的字符串和最开始的字符串是否相同
    def is_palindrome(text):
        text0 = clear(text)
        return text0 == reverse(text0)
    
    # 将数据的字符串中的空白字符和标点符号
    def clear(text):
        # 去掉字符串中的空白字符
        text1 = re.sub('s','',text)
        bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
        # 此为中文标点符号
        punc = "!?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏."
        # string.punctuation 此为英文标点符号
        mark=''.join([punc,string.punctuation])
        bytes1 = mark.encode(encoding='utf-8',errors='strict')
        bytestr = text1.encode(encoding='utf-8',errors='strict')
        # 去掉字符串中的标点符号
        return (bytestr.translate(bytes_tabtrans,bytes1)).decode("utf-8")
    
    # 从客户端输入被检测的字符串
    something = input("Enter text: ")
    if is_palindrome(something):
        print("Yes, it is a palindrome")
    else:
        print("No,it is not a palindrome" )
    
    

    博客有哪里写的不对的地方,多谢留言评论

  • 相关阅读:
    Angular入门到精通系列教程(12)- 路由(Routing)
    Angular入门到精通系列教程(11)- 模块(NgModule),延迟加载模块
    error: file '/boot/grub/i386-pc/normal.mod' not found解决方案
    mysql常用查询
    mysql数据库表中随机生成时间
    成本分析报表
    弹窗维护字段POPUP_GET_VALUES
    返回上一个屏幕
    PM停机时间问题处理
    IP41
  • 原文地址:https://www.cnblogs.com/youchi/p/10345615.html
Copyright © 2011-2022 走看看