Python编程:Python2和Python3下的translate函数字符映射替换
【摘要】 python2 和 python3的不兼容 导致了诸多问题。
喏,一个 translate 都有好几种写法
Python2
ASCII编码
# -*- coding: utf-8 -*-
import string
trantab = string.maketrans("123", "ABC")
s = "123 456"
ret = s.transla...
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
Python3
Python3.4 已经没有 string.maketrans() ,取而代之的是内建函数: str.maketrans()
方式一:通过字符串构建转换表
# 参数: 原始字符表,转换字符表,删除字符表
table = str.maketrans("123", "ABC", "4")
s = "1234"
ret = s.translate(table)
print(ret) # ABC
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
方式二:通过字典构建转换表
dct = { "1": "AA", "2": "BB", "3": "CC"
}
table = str.maketrans(dct)
s = "1234"
ret = s.translate(table)
print(ret) # AABBCC4
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/79355023
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)