Python编程:Python2和Python3下的translate函数字符映射替换
  TEZNKK3IfmPf 2023年11月15日 27 0

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
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
TEZNKK3IfmPf