python中利用字典加密字符串_用str.maketrans给字符串加密?

先说一下得到楼主所期望的输出正确的用法,在用str.maketrans建立映射关系或者说创建加密方式之后,对新的字符串应该用对应的translate进行加密,所以这正确方式应该是:

trantab = str.maketrans("abcde", "12345")

"abcde".translate(trantab)

Out[4]: '12345'

在用maketrans建立了字符一一对应的映射关系之后,把新字符串“abcde”进行转化,得到字符串'12345'

接下来看一下maketrans详细用法:

官方文档:

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

This static method returns a translation tableusable for

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be 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.

Duang,Duang! 敲黑板,划重点了,简单说maketrans定义了几种参数传入格式,返回值是给translate()方法用的,而不是自己~如果只有一个参数,必须是字典格式,比如:{"a": "1", "b": "2"}

2. 如果是两个参数,必须是长度相等的字符串,比如题主这个例子,表示a->1(a映射成1),b->1

3. 如果有三个参数,必须是字符,这个字符在结果中不做转换,返回None。可以看到下面这个例子中e没有被转换

最后在分析楼主两次调用maketrans的输出:

第一次调用实际上返回的是字母和数字的映射关系,是一个字典,key和value都是ascII 编码,a的ascII编码是97,1是49,以次类推

第二次调用实际上是吧这个用ascII 编码进行映射的字典作为传入参数,也就是我们说的传入一个参数的情况,返回依然是映射关系:

希望能帮助到大家。

编辑不容易,看到这了,点个赞呗~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值