python encode() [英] python encode()

查看:136
本文介绍了python encode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

十六进制编解码器是否被排除在python 3.3之外?当我写代码时

Has hex codec been excluded from python 3.3? When I write the code

>>> s="Hallo"
>>> s.encode('hex')
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    s.encode('hex')
LookupError: unknown encoding: hex

这是什么意思?我知道binascii.hexlify()但仍然.encode()方法很好!
任何建议?

What does that mean? I know about binascii.hexlify() but still .encode() method is nice! Any suggestion?

推荐答案

不,使用 encode() to hexlify并不好。

No, using encode() to hexlify isn't nice.

使用十六进制编解码器的方式可以在Python 2中工作,因为您可以在Python 2的8位字符串上调用 encode(),即可以编码已编码的东西。这没有意义。 encode()用于将Unicode字符串编码为8位字符串,而不用于将8位字符串编码为8位字符串。

The way you use the hex codec worked in Python 2 because you can call encode() on 8-bit strings in Python 2, ie you can encode something that is already encoded. That doesn't make sense. encode() is for encoding Unicode strings into 8-bit strings, not for encoding 8-bit strings as 8-bit strings.

在Python 3中,不能再对8位字符串调用 encode(),所以 hex 编解码器变得毫无意义并被删除。

In Python 3 you can't call encode() on 8-bit strings anymore, so the hex codec became pointless and was removed.

尽管理论上可以有一个十六进制编解码器并像这样使用它:

Although you theoretically could have a hex codec and use it like this:

>>> import codecs
>>> hexlify = codecs.getencoder('hex')
>>> hexlify(b'Blaah')[0]
b'426c616168'

使用binascii更容易和更好:

Using binascii is easier and nicer:

>>> import binascii
>>> binascii.hexlify(b'Blaah')
b'426c616168'

这篇关于python encode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆