python2 和 python3的不兼容 导致了诸多问题。
喏,一个 translate 都有好几种写法
Python2ASCII编码
# -*- coding: utf-8 -*-
import string
trantab = string.maketrans("123", "ABC")
s = "123 456"
ret = s.translate(trantab)
print(ret) # ABC 456
unicode编码
unicode 的translate方法的映射表也就是字典的键必须是unicode的位序数
值可以是unicode的位序数、unicode字符串或这None
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
dct = {
ord("1"): "AA",
ord("2"): "BB",
ord("3"): "CC"
}
s = "123456"
ret = s.translate(dct)
print(ret) # AABBCC456
Python3
Python3.4 已经没有 string.maketrans() ,取而代之的是内建函数: str.maketrans()
方式一:通过字符串构建转换表
# 参数: 原始字符表,转换字符表,删除字符表
table = str.maketrans("123", "ABC", "4")
s = "1234"
ret = s.translate(table)
print(ret) # ABC
方式二:通过字典构建转换表
dct = {
"1": "AA",
"2": "BB",
"3": "CC"
}
table = str.maketrans(dct)
s = "1234"
ret = s.translate(table)
print(ret) # AABBCC4
参考: Python2.x和3.x下maketrans与translate函数使用上的不同