Recipe 1.8. Checking Whether a String Contains a Set of Characters(Python Cookbook)

ExpandedBlockStart.gifmaketrans
1 >>> intab = "aeiou"
2 >>> outtab = "12345"
3 >>> from string import maketrans
4 >>> trantab = maketrans(intab, outtab)
5 >>> s = "this is a string example...wow!"
6 >>> print s.translate(trantab)
7 th3s 3s 1 str3ng 2x1mpl2...w4w!

 

1 >>> import itertools
2 >>> def containsAny(seq, aset):
3     for item in itertools.ifilter(aset.__contains__, seq):
4         return True
5     return False
6 
7 >>> containsAny("abcd""ae")
8 True

 

ExpandedBlockStart.gifdifference
 1 >>> def containsAll(seq, aset):
 2     return not set(aset).difference(seq)
 3 
 4 >>> containsAll("abc""ad")
 5 False
 6 >>> containsAll("Abc""Ac")
 7 True
 8 >>> L1 = [1233]
 9 >>> L2 = [1234]
10 >>> set(L1).difference(L2)
11 set([])
12 >>> set(L2).difference(L1)
13 set([4])

 

 

ExpandedBlockStart.gifcode
 1 >>> import string
 2 >>> notrans = string.maketrans('''')
 3 >>> def containsAny(astr, strset):
 4     return len(strset) != len(strset.translate(notrans, astr))
 5 
 6 >>> def containsAll(astr, strset):
 7     return not strset.translate(notrans, astr)
 8 
 9 >>> "abc".translate(notrans, "ac")
10 'b'
11 >>> containsAny("abcde""af")
12 True
13 >>> containsAll("abcef""aef")

 

转载于:https://www.cnblogs.com/zhtf2014/archive/2010/12/20/1911948.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值