python2.7 maketrans工作原理

今天用到了python str maketrans,順道看了一下實現原理,做一下記錄

# Case conversion helpers
# Use str to convert Unicode literal in case of -U
# 把ascii表的字符放到list中
l = map(chr, xrange(256))
# 把list轉換爲str
_idmap = str('').join(l)
del l
# Construct a translation string

...

_idmapL = None
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.

    """
    # 保證fromstr和tostr長度一致,不然下面替換的代碼就會報錯
    if len(fromstr) != len(tostr):
        raise ValueError, "maketrans arguments must have same length"
    global _idmapL
    # 再把ascii的字符串轉換爲list
    if not _idmapL:
        _idmapL = list(_idmap)
    # 列表切片產生的是列表的副本,與原列表不是同一份空間,對L的操作不會影響到_idmapL
    L = _idmapL[:]
    # 把fromstr每一個需要替換的字符在ascii表中的位置放到fromstr的list中
    fromstr = map(ord, fromstr)
    # 執行具體的替換操作
    for i in range(len(fromstr)):
        L[fromstr[i]] = tostr[i]
    # 返回替換後的ascii表字符串
    return ''.join(L)

大概思路是,把ascii表放到一個list中,然後把list中需要替換的字符,替換爲新的字符。所以纔會要求fromstr和tostr大小一致,該方法返回的長度固定爲256。

這個方法是結合str.translate()一起使用的,maketrans生成一個字符字典,str.translate()方法根據這個字典,替換str中相關的字符,具體的替換操作,另起一篇。

ord函數解釋:http://www.runoob.com/python/python-func-ord.html
map函數解釋:http://www.runoob.com/python/python-func-map.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章