编写一个Python程序来检查给定的字符串是否是回文[关闭]

问题描述 投票:0回答:2

输入和输出示例: 输入:“一个人计划修建巴拿马运河”

输出:“该字符串是回文。”

输入:“你好,世界!”

输出:“该字符串不是回文。”

要求: 该程序应该处理各种情况,例如: 忽略空格和标点符号。 将大写字母和小写字母视为相同。 奖金挑战: 修改程序以返回在较长字符串中找到的回文(如果适用)。

我尝试过的: 回文检查:我实现了一个 Python 程序来检查字符串是否为回文。 测试用例:我使用各种输入测试了程序,包括: “一个人计划修建巴拿马运河” “你好世界!” 《赛车》 “没有柠檬,就没有甜瓜” 我的期望: 对于输入“一个人计划一条巴拿马运河”,我希望程序返回它是一个回文,因为当去掉空格和标点符号时,它向前和向后读取相同的内容。 对于输入“Hello, World!”,我希望输出表明它不是回文。 对于“赛车”,我希望它能够确认它是一个回文。 对于“没有柠檬,没有瓜”,我预计它也会确认它是一个回文。

python palindrome
2个回答
-1
投票

为了满足您的要求,您需要首先过滤掉您不想要的所有内容:

  1. 将所有内容转为小写
"Hello World!".lower()
# Output: hello world!
  1. 使用
  2. 过滤掉非字母数字字符
''.join(filter(str.isalnum, "!!!hello!!!"))
# Output: hello

结合你得到:

''.join(filter(str.isalnum, "!!!Hello World!!!")).lower()
# Output: helloworld

现在通过使用切片检查字符串的反转是否与原始字符串相同来检查它是否是回文:

word = 'this is not a palindrome'
word[::-1]
# Output: emordnilap a ton si siht 

总而言之,你得到:

word = input('Enter some word: ') # Input word or just set it to a string
word = ''.join(filter(str.isalnum, word)).lower() # Filter characters
if word[::-1] == word: # Reverse and check if it is the same
    print('Palindrome')
else:
    print('Not a palindrome')
# Input: racecar -> Palindrome
# Input: Hello World! -> Not a palindrome

-1
投票

我认为你的问题与这个问题没有什么不同: 如何使用Python逻辑检查回文

,但这是我的答案: 您必须反转字符串并检查原始字符串是否与反转后的字符串相同:

def is_palindrome(txt: str) -> bool: # Takes a string and returns a boolean
    reversed_txt: str = txt[::-1]
    return txt == reversed_txt

这是一个示例用法:

print(is_palindrome("12321")) # True
print(is_palindrome("racecar")) # True

现在你只需要找到一种方法来删除多余的字符(“空格”“,”“。”'!““?”等)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.