歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python的maketrans() 方法

Python的maketrans() 方法

日期:2017/3/1 9:18:49   编辑:Linux編程

描述

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的文章您也可能喜歡,不妨看看:

Linux下Python的安裝以及注意事項 http://www.linuxidc.com/Linux/2015-11/124861.htm

Ubuntu 14.04 下安裝使用Python rq模塊 http://www.linuxidc.com/Linux/2015-08/122441.htm

無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved