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

代码如下:

#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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书山登峰人

精品不易

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值