Python maketrans()返回一个转换表,该表将intabstring中的每个字符映射到outtab字符串中相同位置的字符。然后将该表传递给translate()函数。

注意-Intab和Outtab必须具有相同的长度。

maketrans() - 语法

str.maketrans(intab, outtab)
  • intab      -  这是具有实际字符的字符串。

  • Outtab   -  这是具有相应映射字符的字符串。

maketrans() - 返回值

此方法返回要使用的Translate()函数的数据。

maketrans() - 示例

以下示例显示maketrans()方法的用法。在这种情况下,字符串中的每个元音都被其元音位置-替换

#!/usr/bin/python

from string import maketrans   # Required to call maketrans function.

intab="aeiou"
outtab="12345"
trantab=maketrans(intab, outtab)

str="this is string example....wow!!!"
print str.translate(trantab)

当无涯教程运行上面的程序时,它产生以下输出-

th3s 3s str3ng 2x1mpl2....w4w!!!

参考链接

https://www.learnfk.com/python/string-maketrans.html