python中的maketrans和translate

参考:http://wangwei007.blog.51cto.com/68019/1242206


maketrans和translate在某一方面和string.replace很相似

maketrans和translate使用:

#string.maketrans(from, to): return  a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to;from and to must have the same length.
#string.translate(s, table[, deletechars]): Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.

import string

str1 = '123[abc]123'
table = string.maketrans('[]', '""') #from 和 to一一对应
tmp_str = string.translate(str1, table)
print tmp_str  #123"abc"123


maketrans和translate结合可以一次替换多个字符,string.replace只能每次替换一个字符

tmp_str1 = string.replace(str1, '[' , '"')
tmp_str1 = string.replace(tmp_str1, ']' , '"')
print tmp_str1  #123"abc"123


另外,string.replace可以控制替换几次

tmp_str2 = string.replace(str1, '1', 'A', 1) #第四个参数,表示替换几次
print tmp_str2 #A23[abc]123



原文地址:https://www.cnblogs.com/zhangjianzhi/p/3820862.html