Python maketrans()方法

Python 教程 · 2019-02-02 15:13:38

描述

Python maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

注:两个字符串的长度必须相同,为一一对应的关系。

语法

maketrans()方法语法:

str.maketrans(intab, outtab)

参数

  • intab -- 字符串中要替代的字符组成的字符串。
  • outtab -- 相应的映射字符的字符串。

返回值

返回字符串转换后生成的新字符串。

实例

以下实例展示了使用maketrans() 方法将所有元音字母转换为指定的数字:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from string import maketrans   # 必须调用 maketrans 函数。

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

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

以上实例输出结果如下:

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

点击查看所有 Python 教程 文章: https://www.codercto.com/courses/l/8.html

查看所有标签

Computer Age Statistical Inference

Computer Age Statistical Inference

Bradley Efron、Trevor Hastie / Cambridge University Press / 2016-7-21 / USD 74.99

The twenty-first century has seen a breathtaking expansion of statistical methodology, both in scope and in influence. 'Big data', 'data science', and 'machine learning' have become familiar terms in ......一起来看看 《Computer Age Statistical Inference》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具