如何使大小写不敏感? [英] How to make case insensitive?
本文介绍了如何使大小写不敏感?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int_string = input("What is the initial string? ")
int_string = int_string.lower()
如何使输入的大小写不敏感
How do I make the input case insensitive
推荐答案
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
来填充一些这样的方法。
If you don't like all the repetitive code, you can utilise total_ordering
to fill in some of the methods like this.
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"
这篇关于如何使大小写不敏感?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文