如何在不转换为 int 的情况下获取字节串中的单个字节

How to get a single byte in a string of bytes, without converting to int

我有一个像 str_of_bytes = b'\x20\x64\x20' 这样的字节串,我想从中提取第二个元素。 如果我做 str_of_bytes[1],我得到的是 int 100。 我如何才能获得 b'\x64',而不必将 int 重新转换为 bytes

将其提取为一个范围:

str_of_bytes[1:2]

结果:

b'd'

这与b'\x64'

相同

请注意,我假设您使用的是 Python 3。Python 2 的行为不同。