您当前的位置: 首页 >  Python

Python编程:Python2和Python3下的translate函数字符映射替换

彭世瑜 发布时间:2018-02-23 17:03:29 ,浏览量:3

python2 和 python3的不兼容 导致了诸多问题。

喏,一个 translate 都有好几种写法

Python2

ASCII编码

# -*- 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函数使用上的不同

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 3浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.2774s