python提取部分字符串三参数_python3 字符串属性(三)

maketrans 和 translate的用法(配合使用)

下面是python的英文用法解释

maketrans(x, y=None, z=None, /)

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode

ordinals (integers) or characters to Unicode ordinals, strings or None.

Character keys will be then converted to ordinals.

If there are two arguments, they must be strings of equal length, and

in the resulting dictionary, each character in x will be mapped to the

character at the same position in y. If there is a third argument, it

must be a string, whose characters will be mapped to None in the result

S.translate(table) -> str

Return a copy of the string S, where all characters have been mapped

through the given translation table, which must be a mapping of

Unicode ordinals to Unicode ordinals, strings, or None.

Unmapped characters are left untouched. Characters mapped to None

are deleted.

makestans返回一个给translate用的映射表,translate根据映射表构造新的字符串。

makestran根据参数的个数有三种使用方法:

1)一个参数情况,参数必须是字典

一个字符转换成一个字符

1 >>> a='qwerabc2348'

2 >>> d={'a':'A','q':'Q'} #转换映射表3 >>> tans=str.maketrans(d) #转换为translate可以使用的映射表4 >>>tans5 {97: 'A', 113: 'Q'} #translate可以使用的映射表6 >>>a.translate(tans)7 'QwerAbc2348' #转换后的结果

一个字符转换为多个字符

1 >>> d2={'a':'*A*','q':'*Q*'}2 >>> tans2=str.maketrans(d2)3 >>>tans24 {97: '*A*', 113: '*Q*'}5 >>>a.translate(tans2)6 '*Q*wer*A*bc2348

一个字符转换为None,效果为过滤删除字符

1 >>> d3={'a':None,'q':None}2 >>> tans3=str.maketrans(d3)3 >>>tans34 {97: None, 113: None}5 >>>a.translate(tans3)6 'werbc2348'

2)两个参数的情况,参数(字符串)必须长度相等。

1 >>> a='acbsdwf124'

2 >>> tans4=str.makestrans('abc','ABC')3 >>> tans4=str.maketrans('abc','ABC')4 >>>tans45 {97: 65, 98: 66, 99: 67}6 >>>a.translate(tans4)7 'ACBsdwf124'

3)三个参数的情况,前两个参数效果和2)相同,第三个参数为要过滤删除的字符表(第三个参数都映射为None)

1 >>>a2 'acbsdwf124'

3 >>> tans5=str.maketrans('abc','ABC','1234')4 >>>tans55 {97: 65, 98: 66, 99: 67, 52: None, 51: None, 49: None, 50: None}6 >>>a.translate(tans5)7 'ACBsdwf'

4)映射表中的数字为unicode编码数字

1 >>> ord('a')2 97

3 >>> chr(97)4 'a'

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值