Ray's playground

 

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

maketrans
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

 

difference
 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])

 

 

code
 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")

 

posted on 2010-12-20 22:18  Ray Z  阅读(359)  评论(0编辑  收藏  举报

导航