int_string = input("What is the initial string? ")
int_string = int_string.lower()
如何使输入不区分大小写
int_string = input("What is the initial string? ")
int_string = int_string.lower()
如何使输入不区分大小写
class CaseInsensitiveStr(str):
def __eq__(self, other):
return str.__eq__(self.lower(), other.lower())
def __ne__(self, other):
return str.__ne__(self.lower(), other.lower())
def __lt__(self, other):
return str.__lt__(self.lower(), other.lower())
def __gt__(self, other):
return str.__gt__(self.lower(), other.lower())
def __le__(self, other):
return str.__le__(self.lower(), other.lower())
def __ge__(self, other):
return str.__ge__(self.lower(), other.lower())
int_string = CaseInsensitiveStr(input("What is the initial string? "))
如果你不喜欢所有重复的代码,你可以利用total_ordering
像这样填写一些方法。
from functools import total_ordering
@total_ordering
class CaseInsensitiveMixin(object):
def __eq__(self, other):
return str.__eq__(self.lower(), other.lower())
def __lt__(self, other):
return str.__lt__(self.lower(), other.lower())
class CaseInsensitiveStr(CaseInsensitiveMixin, str):
pass
测试用例:
s = CaseInsensitiveStr("Foo")
assert s == "foo"
assert s == "FOO"
assert s > "bar"
assert s > "BAR"
assert s < "ZAB"
assert s < "ZAB"
问题是由于此处input()
所述的功能
此函数不会捕获用户错误。如果输入在语法上无效,
SyntaxError
则会引发 a。如果评估期间出现错误,可能会引发其他异常。考虑将该
raw_input()
功能用于用户的一般输入。
所以只需使用raw_input()
,一切正常