检查字符串中是否包含某字符集合中的字符
任务:
检查字符串中是否出现了某个字符集合中的字符
解决方案:
方案一:
import itertools def containAny(seq,aset):
for item in itertools.ifilter(aset.__contains__,seq):
return True
return False if __name__ == "__main__":
l1 = list('python')
l2 = set('x')
print containAny(l1,l2)
方案二:
l1 = list('python')
l2 = set('df')
def containAny(seq,aset):
for a in seq:
if a in aset: return True
return False
print containAny(l1,l2)
简化字符串的translate方法的使用
任务:
用字符串的translate方法来进行快速编码,将string.maketrans函数简单封装。
解决方案:
import string
def translator(frm = '',to = '',delete = '' ,keep = None):
if len(to) == 1:
to = to*len(frm)
trans = string.maketrans(frm, to)
if keep is not None:
allchars = string.maketrans('','')
delete = allchars.translate(allchars,keep.translate(allchars,delete))
def translate(s):
return s.translate(trans,delete)
return translate