string 模块 maketrans函数 和 translate函数的用法

本文详细解析了Python中字符串方法translate和maketrans的使用方式,包括基本语法、实例演示以及如何对字符串进行更灵活的过滤与转换。通过封装函数,实现了对特定字符集的高效处理,展示了解决实际问题的实用技巧。
部署运行你感兴趣的模型镜像

1.
string.maketrans(from,to)
Return a translation table suitable for passing totranslate(), that will map each character infrominto the character at the same position into;fromandtomust have the same length.

2.
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 isNone, then only the character deletion step is performed.

例子1:
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!!!


例子2:

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, 'xm');



输出结果:

th3s 3s str3ng 21pl2....w4w!!!


例子3:
引用自:Python Cookbook 第二版, 1.9节
使用字符串的方法translate,为了使用更方便,对它进行一个封装。

import string
def translator(frm='', to='', delete='', keep=None):
if len(to) == 1:
to = to*len(frm)
trans = string.maketrans(frm, to)

if keep is not None:
#定义一个翻译表allchars,且指定不须翻译。
allchars = string.maketrans('', '')
delete = allchars.translate(allchars, keep.translate(allchars, delete))

def translate(s):
return s.translate(trans, delete)

return translate


NameAndID = 'FuQiang 61450597'

degits_only = translator(keep=string.digits)
print type(degits_only)

ID = degits_only(NameAndID)
print ID

no_digits = translator(delete=string.digits)
name = no_digits(NameAndID)
print name

digits_to_hash = translator(frm=string.digits, to='*')
hideID = digits_to_hash(NameAndID)
print hideID

delete_keep = translator(delete='Fu', keep = 'qiang6145')
partStr = delete_keep(NameAndID)
print partStr

输出结果 :
>>>
<type 'function'>
61450597
FuQiang
FuQiang ********
iang61455
>>>

例子4:
引用自:Python Cookbook 第二版, 1.10节

过滤字符串中不属于指定集合的字符

import string

#maketrans函数是一个创建翻译表的工具函数。
allchars = string.maketrans('', '')

def makefilter(keep):
delchars = allchars.translate(allchars, keep)
def thefilter(s):
return s.translate(allchars, delchars)
return thefilter

if __name__ == '__main__':
filterStr = makefilter('abcdefg')
print filterStr('FuQiang')

输出:
>>>
ag
>>>








您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值