001_024 Python 让某些字符串大小写不敏感 如比较和查询不敏感 其他敏感

来源:互联网 发布:lego ev3编程中文下载 编辑:程序博客网 时间:2024/06/09 00:33

代码如下:

#encoding=utf-8print '中国'#让某些字符串大小写不敏感 如比较和查询不敏感 其他敏感#方案 封装为类class iStr(str):    '''大小写不敏感的字符串类                    类似str 比较和查询大小写不敏感    '''    def __init__(self,*args):        self.lowered = str.lower(self)    def __repr__(self):        return '%s(%s)' % (type(self).__name__,str.__repr__(self))    def __hash__(self):        return hash(self.lowered)def _make_case_insensitive(name):    str_meth = getattr(str,name)    def x(self,other,*args):        try: other = other.lower()        except(TypeError, AttributeError, ValueError) :pass        return str_meth(self.lowered,other,*args)    setattr(iStr,name,x)for name in 'eq lt le ge gt ne contains'.split():    _make_case_insensitive('__%s__' % name)for name in 'count endswith find index rfind rindex startswith'.split():    _make_case_insensitive(name)del _make_case_insensitivea = iStr('abcA')b = iStr('aBca')print a == ba = str('abcA')b = str('aBca')print a == b

打印结果如下:

中国
True
False

0 0
原创粉丝点击