Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 将字符串逐字转换为字节_String_Python 3.x_Encoding_Byte - Fatal编程技术网

String 将字符串逐字转换为字节

String 将字符串逐字转换为字节,string,python-3.x,encoding,byte,String,Python 3.x,Encoding,Byte,我想要一个字符串,例如: '\\xeb\\x4d' 并将其转化为: b'\xeb\x4d' 如果我这样做: bytes('\\xeb\\x4d', 'utf-8') 我得到: b'\\xeb\\x4d' 我需要做以下事情: something('\\xeb\\x4d') == b'\xeb\x4d' 给予 因为 '\x4d' == 'M' 请注意,latin1是Unicode的前256个码点,因此编码Unicode的前256个字节将给出与原始码点相同的字节值。您可以直接使用lati

我想要一个字符串,例如:

'\\xeb\\x4d' 
并将其转化为:

b'\xeb\x4d'
如果我这样做:

bytes('\\xeb\\x4d', 'utf-8')
我得到:

b'\\xeb\\x4d'
我需要做以下事情:

something('\\xeb\\x4d') == b'\xeb\x4d'
给予

因为

'\x4d' == 'M'

请注意,
latin1
是Unicode的前256个码点,因此编码Unicode的前256个字节将给出与原始码点相同的字节值。

您可以直接使用
latin1
“\xeb\x4d”进行编码。encode('latin1')
我的原始字符串已跳过反斜杠,这就是我需要使用“unicode\u escape”编解码器解码的原因。您的输入是
'\\xeb\\x4d'
还是
'\xeb\x4d'
?您可以在问题的正文中同时使用这两个选项。我的输入是
'\\xeb\\x4d'
。我把我的问题按顺序编辑了一下。很抱歉给你带来困惑,谢谢你提醒我。谢谢你的回答。关于latin1编解码器的解释帮助我理解了到底发生了什么!
b'\xebM'
'\x4d' == 'M'
>>> a = '\\xeb\\x4d'   # a Unicode string
>>> a.encode('latin1') # get a byte string
b'\\xeb\\x4d'
>>> a.encode('latin1').decode('unicode_escape') # unescape, get a Unicode string
'ëM'
>>> a.encode('latin1').decode('unicode_escape').encode('latin1') # get a byte string
b'\xebM'
>>> a.encode('latin1').decode('unicode_escape').encode('latin1') == b'\xeb\x4d'
True