现在的位置: 首页 > 综合 > 正文

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

2018年02月15日 ⁄ 综合 ⁄ 共 772字 ⁄ 字号 评论关闭

代码如下:

#encoding=utf-8
print '中国'

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

#方案 封装为类

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_insensitive

a = iStr('abcA')
b = iStr('aBca')

print a == b

a = str('abcA')
b = str('aBca')

print a == b

打印结果如下:

中国
True
False

抱歉!评论已关闭.