python中的translate_Python translate()方法

 2023-09-15 阅读 21 评论 0

摘要:描述 Python translate() 方法根据 maketrans() 方法给出的字符映射转换表转换字符串中的字符。 语法 translate() 方法语法: Python3中: S.translate(table) Python2中: S.translate(table[,delchars]) 参数 table -- 字符映射转换表表,是通过 m

描述

Python translate() 方法根据 maketrans() 方法给出的字符映射转换表转换字符串中的字符。

语法

translate() 方法语法:

Python3中:

S.translate(table)

Python2中:

S.translate(table[,delchars])

参数

table -- 字符映射转换表表,是通过 maketrans() 方法转换而来的。

delchars -- 可选参数,表示要删除的字符组成的字符串。

返回值

返回根据 maketrans() 方法给出的字符映射转换表转换后的字符串,如果给出delchars参数,则会删除这些字符然后进行转换。

实例

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

Pyhon3中:

#!/usr/bin/python3

intab = "aeiou"

outtab = "12345"

deltab = "thw"

trantab1 = str.maketrans(intab,outtab) # 创建字符映射转换表

trantab2 = str.maketrans(intab,outtab,deltab) #创建字符映射转换表,并删除指定字符

test = "this is string example....wow!!!"

print(test.translate(trantab1))

print(test.translate(trantab2))

以上实例输出结果如下:

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

3s 3s sr3ng 2x1mpl2....4!!!

Python2中:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import string # 导入string模块

intab = "aeiou"

outtab = "12345"

deltab = "thw"

trantab = string.maketrans(intab,outtab) # 创建字符映射转换表

test = "this is string example....wow!!!";

print test.translate(trantab);

print test.translate(trantab,deltab); # Python2中,删除指定字符在 translate() 方法中

以上实例输出结果如下:

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

3s 3s sr3ng 2x1mpl2....4!!!

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/58507.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息