【问题标题】:Palindrome string. How to exclude non strings. [duplicate]回文串。如何排除非字符串。 [复制]
【发布时间】:2018-08-29 22:12:39
【问题描述】:

如果给定的字符串是回文,我已经修改了以下函数以返回。我也有它,不包括大写、空格和标点符号。如果用户输入非字符串,我如何修改它以返回“false”。

import string

def remove_punctuations(word):
    return "".join(i.lower() for i in word if i in string.ascii_letters)

def reverse(text):
    return text[::-1]

def is_palindrome(text):
    text = remove_punctuations(text)
    return text==reverse(text)

# where I am entering the string
something = "12.5"

if (is_palindrome(something)):
   print("True")
else:
   print("False")

# some test cases
>>> isPalindrome("alula")
True
>>> isPalindrome("love")
False
>>> isPalindrome(12)
False
>>> isPalindrome(12.21)
False

另外我该如何调整这段代码,以便我可以输入 is_palindrome(something),而不是手动输入“something”

【问题讨论】:

  • 作为设计建议:不要。只需记录它需要一个字符串,然后让它崩溃,但是如果给定一些非字符串,它就会崩溃。

标签: python string python-3.x


【解决方案1】:

您有多种选择。您可以使用 input()、raw_input()、argparse、optparse 从用户那里获取输入。
关于输入的类型,可以查看python的isinstance()方法。

【讨论】:

    猜你喜欢
    • 2020-04-14
    • 1970-01-01
    • 2010-11-26
    • 2018-12-02
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2014-01-26
    相关资源
    最近更新 更多