Strange notation for Python 3 bytes(Python 3 字节的奇怪符号)
问题描述
有人可以识别这些 bytes 的符号是什么吗?乍一看,我倾向于认为十六进制",但我不认识
xf1Y 和
e1fl
之类的东西是什么:
b'vyxe9xb5xa2xbaxf1Yxe8xe1flx1dx87xacC'
我在使用
some_text.encode('utf-8')
编码时得到这个.我正在尝试获取可以传递给使用 Python 2 字节字符串的加密方法的字节.
解决方案你说得对——它是一种十六进制表示法.
在字节文字中,任何不能用可打印的 ASCII 字符(或标准转义符
、
或
之一)表示的字节>
) 表示为xNN
,其中 NN 是字节的 2 位十六进制表示.让您感到困惑的是,您弄错了,例如
<预><代码>>>>len(b'xf1Y')2>>>[bytes([b]) for b in b'xf1Y'][b'xf1', b'Y']xf1Y
用于单个转义序列,实际上它代表两个单独的字节:如果你遍历一个字节对象,你会得到字节的整数值:
<预><代码>>>>列表(b'vyxe9xb5xa2xbaxf1Yxe8xe1flx1dx87xacC')[118, 121, 233, 181, 162, 186, 241, 89, 232, 225, 102, 108, 29, 135, 172, 67]>>>字节([118])b'v'>>>字节([121])经过'>>>字节([233])b'xe9'
Python 字符串和字节对象中的转义序列的文档 有更多关于 Python 理解的转义序列的信息(尽管以上是它用来表示字节对象的唯一信息).
Can someone identify what this notation for these bytes
is? At first glance, I tend to think "hexadecimal", but I don't recognize what things like xf1Y
and e1fl
are:
b'vyxe9xb5xa2xbaxf1Yxe8xe1flx1dx87xacC'
I get this when I encode things using some_text.encode('utf-8')
.
I am trying to get bytes that I can pass to cryptography methods that worked with Python 2's byte strings.
You're right – it's a hexadecimal notation.
In a bytes literal, any byte which can't be represented by a printable ASCII character (or one of the standard escapes
,
or
) is represented as xNN
, where NN is the 2-digit hexadecimal representation of the byte.
What's confusing you is that you're mistaking e.g. xf1Y
for a single escape sequence, when in fact it represents two separate bytes:
>>> len(b'xf1Y')
2
>>> [bytes([b]) for b in b'xf1Y']
[b'xf1', b'Y']
If you iterate over a bytes object, you'll get the integer values of the bytes back:
>>> list(b'vyxe9xb5xa2xbaxf1Yxe8xe1flx1dx87xacC')
[118, 121, 233, 181, 162, 186, 241, 89, 232, 225, 102, 108, 29, 135, 172, 67]
>>> bytes([118])
b'v'
>>> bytes([121])
b'y'
>>> bytes([233])
b'xe9'
The documentation for escape sequences in Python string and bytes objects has a little more information on escape sequences Python understands (although those above are the only ones it uses to represent bytes objects).
这篇关于Python 3 字节的奇怪符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 3 字节的奇怪符号
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01