Python2中的string.maketrans


搜索关键字:

python string.maketrans

参考链接:
参考解答:

Python中的 string.maketrans(from, to) 用于将参数中的 from 映射成 to (对位映射,所以需要’from’和’to’的长度一致),然后传递给 string.translate() 进行处理。类似于Linux的 tr 命令(tr ‘set1’ ‘set2’)。

不要使用 lowercase 和 uppercase 作为 string.maketrans() 的参数,因为在某些情况下它们的长度是不一致的。如果要进行大小写的转换,请使用 str.lower() 和 str.upper() 方法

astr = 'How can you tell an extrovert from an introvert at NSA?'

import string
rot13 = string.maketrans(
			u"ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz",
			u"NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm"
		)
print astr.translate(rot13)

print astr.encode('rot13')

import codecs
print codecs.encode(astr, 'rot_13')
注意:

string.translate() 在 Python3 中已经被废弃了

,

《“Python2中的string.maketrans”》 有 1 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注