str.maketrans(x[, y[, z]])

本文详细解析Python中str.maketrans()函数的用法,包括单参数、双参数及三参数模式下如何创建转换表,并应用于字符串翻译。通过实例演示不同参数组合下的映射规则和特殊注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传入参数x,y,z
当传入一个参数既x时:

transtab = str.maketrans({'a':'b'})
news = 'apple'
print (news.translate(transtab))

必须使用字典传入参数而且字典只能为整数或者一个字符
当传入两个参数时:

transtab = str.maketrans('ap','bs')
news = 'apple'
print (news.translate(transtab))

这时就可以随意映射,注意x,y必须具有相同字节数
当传入三个参数时:

transtab = str.maketrans('ap','bs','al')
news = 'apple'
print (news.translate(transtab))
》》sse

当z中有与x中重复的x优先映射到None有与映射后相同的将相同的映射结果变成None
z字节数可以与x,y不一致

下面是原描述:

str.maketrans(x, y, z)
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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值