您的位置:首页 > 编程语言 > Python开发

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

2014-03-12 19:37 399 查看
代码如下:

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐