string模块2 - maketrans()

来源:互联网 发布:价格监控软件开发 编辑:程序博客网 时间:2024/05/22 03:48

通过translate()函数进行转换,生成一个合适转换列表。这个函数有两个参数,第一个参数的每个字符将被映射到第二个参数的对应位置。两个参数必须有相同的长度。


import string

leet = string.maketrans('abegiloprstz','463611092572')

s = 'The quick brown fox jumped over the lazy dog'

print s

print s.translate(leet)

结果:

The quick brown fox jumped over the lazy dog
Th3 qu1ck 620wn f0x jum93d 0v32 7h3 142y d06


def maketrans(fromstr, tostr):

        """maketrans(frm, to) -> string

        Return a translation table (a string of 256 bytes long)

        suitable for use in string.translate. The strings frm and to

        must be of the same length.

        """

        if len(fromstr) != len(tostr):

            raise ValueError, "maketrans arguments must have same length"

        global _idmapL

        if not _idmapL

            _idmapL = list(_idmap)

        L = _idmapL[:]

        fromstr = map(ord, fromstr)

        for i in range(len(fromstr)):

            L[fromstr[i]] = tostr[i]

        return ''.join(L)

原创粉丝点击