python中maketrans和translate的用法

例1.首先说下maketrans函数是生成一个翻译表,比如将‘abc',按照顺序翻译成'ABC'。就可以这样写

import string

t=string.maketrans('abc','ABC')

将字符'a'->'A','b'->'B','c'->'C'。

然后使用translate函数

’abc123‘.translate(t,'123')。translate函数的第一个参数要求是翻译表,这里为之前定义的t,然后使用第二个参数将’123‘从字符串’abc123‘中过滤掉。

那么translate的执行顺序是:先从字符串只过滤掉第二个参数的字符,然后对过滤后的字符串进行t所示的翻译。结果为:ABC


例2.现在我想过滤字符串中不属于指定集合的字符

给定一个需要保留的字符串的集合,构建一个过滤函数,并可将其应用于字符串,返回一个s的拷贝,该拷贝只含指定字符集合的元素

首先定义一个翻译表,指明’无需翻译‘,allchars=string.maketrans('','')

  delchars=allchars.translate(allchars,'meng')//delchars包含了除’meng‘之外的所有字符。

然后就可以使用translate函数来完成。

 ’me32n315g123‘.translate(allchars,delchars)//就会返回meng字符串。

源码:

# Character translation through look-up table. def translate(s, table, deletions=""): """translate(s,table [,deletions]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletions are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. The deletions argument is not allowed for Unicode strings. """ if deletions or table is None: return s.translate(table, deletions) else: # Add s[:0] so that if s is Unicode and table is an 8-bit string, # table is converted to Unicode. This means that table *cannot* # be a dictionary -- for that feature, use u.translate() directly. return s.translate(table + s[:0])

# Construct a translation string _idmapL = None def maketrans(fromstr, tostr): """maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long) suitable for use in string.translate. The strings frm and to must be of the same length. """ if len(fromstr) != len(tostr): raise ValueError, "maketrans arguments must have same length" global _idmapL if not _idmapL: _idmapL = list(_idmap) L = _idmapL[:] fromstr = map(ord, fromstr) for i in range(len(fromstr)): L[fromstr[i]] = tostr[i] return ''.join(L)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值