如何使案例不敏感?

时间:2013-03-14 02:36:09

标签: python case-insensitive

int_string = input("What is the initial string? ")
int_string = int_string.lower()

如何使输入不区分大小写

2 个答案:

答案 0 :(得分:4)

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"

答案 1 :(得分:0)

问题是由于{(3}}

所述的input()函数
This function does not catch user errors. If the input is not syntactically valid,
a SyntaxError will be raised. Other exceptions may be raised if there is an error 
during evaluation.


Consider using the raw_input() function for general input from users.

所以只需使用raw_input(),一切正常