python集合元素可以是字符串吗_001_010 Python 过滤字符串中不属于指定集合的元素 | 学步园...

代码如下:

#encoding=utf-8

print '中国'

#输出字符串中属于某一个集合的字符 not support unicode

print '不支持unicode'

import string

allchars = string.maketrans('','')

def makefilter(keep):

delchars = allchars.translate(allchars,keep)

def thefilter(s):

return s.translate(allchars,delchars)

return thefilter

just_aeio = makefilter('aeiouy')

print just_aeio('fouadkjf;laksjdf;lj;lka中国')

#print just_aeio(u'fouadkjf;laksjdf;lj;lka中国') #不能使用

print '支持unicode'

#处理Unicode字符串 上面代码不适用

import sets

class Keeper(object):

def __init__(self,keep):

self.keep = sets.Set(map(ord,keep))

def __getitem__(self,n):

if n not in self.keep:

return None

return unichr(n)

def __call__(self,s):

return unicode(s).translate(self)

make_keeper = Keeper

ujust_aeio = make_keeper(u'aeiouy国')

print ujust_aeio(u'foadfasa中国')

打印结果如下:

中国

不支持unicode

ouaaa

支持unicode

oaaa国

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值