Python 回文字符串。如何排除非字符串。
我修改了以下函数,以返回给定字符串是否为回文。我也有它,不包括大小写、空格和标点符号。如果用户输入非字符串,我如何修改此项以返回“false”Python 回文字符串。如何排除非字符串。,python,string,python-3.x,Python,String,Python 3.x,我修改了以下函数,以返回给定字符串是否为回文。我也有它,不包括大小写、空格和标点符号。如果用户输入非字符串,我如何修改此项以返回“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_palindrom
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_回文(something),而不是手动输入“something”这里有多个选项。您可以使用input()、raw_input()、argparse、optpasse从用户获取输入。
关于输入的类型,您可以签出python的isinstance()方法。作为设计建议:不要。只需记录它需要一个字符串,并让它崩溃,但如果给定非字符串,它会崩溃。