oflyhigh avatar

每天进步一点点:字符串(str)转字节型数据(bytes)的几种写法

oflyhigh

Published: 13 May 2020 › Updated: 13 May 2020每天进步一点点:字符串(str)转字节型数据(bytes)的几种写法

每天进步一点点:字符串(str)转字节型数据(bytes)的几种写法

还记得鲁迅小说《孔乙己》中提到的茴香豆的“回字有四样写法”吗?孔乙己觉得自己掌握了茴香豆的几种写法,是一个有学识有文化的人。


(图源 :pixabay)

今天在写一段HMAC代码时,直接就用了

digest = hmac.new(key.encode('utf-8'), msg.encode('utf-8'), digestmod='sha256').hexdigest()

然后突然想起来我以前习惯这样用:

hmac.new(bytes(key,'utf-8') , bytes(msg, 'utf-8'), digestmod='sha256').hexdigest()

也就说说,把字符串(str)转成二进制数据/字节型数据(bytes),有两种方法,那么这两种方法有什么区别呢?

为了搞懂这个区别,我查了半天资料,然而实在觉得是没啥区别(至少在Python 3.6以后是这样),但是却被我又发现了两种转换方法。

我把它们整理一下,这样我就掌握了四种写法了,测试代码如下:

a = "苍茫的天涯是我的爱!"
print(type(a))

b = bytes(a, 'utf-8')
print(b)
print(type(b))

c = a.encode('utf-8')
print(c)
print(type(c))

d = str.encode(a, 'utf-8')
print(d)
print(type(d))

import codecs
e = codecs.encode(a, 'utf-8')
print(e)
print(type(e))

输出如下:

image.png

也就是说在python3中,无论是使用bytes(a, 'utf-8') 还是a.encode('utf-8') 还是 str.encode(a, 'utf-8') 或者codecs.encode(a, 'utf-8')都可以将字符串转换成bytes。

在测试完成后,我突然觉得我简直就是现代版的孔乙己啊,知道一种用法就行呗,非得学到四种没啥差别的用法,以后用到时,除了懵,还有啥好处呢?

当然也有可能我没掌握这几种用法真的差异和精髓,研究得不够透彻,不过我却不想研究下去了,有知道的朋友说一声吧。

当然了,顺便又重读了一遍《孔乙己》,说不出有啥感受,倒是有点伤感/(ㄒoㄒ)/~~

相关链接

Leave 每天进步一点点:字符串(str)转字节型数据(bytes)的几种写法 to:

Written by

Programmer, Maker, Freelancer, Witness. Make friends, Make money, Make life better!

Read more #cn posts


Best Posts From oflyhigh

We have not curated any of oflyhigh's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From oflyhigh