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


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
>>>








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值