【问题标题】:Convert string to bytes literally从字面上将字符串转换为字节
【发布时间】:2015-07-19 20:10:03
【问题描述】:

我想取一个字符串,比如:

'\\xeb\\x4d' 

并把它变成:

b'\xeb\x4d'

如果我这样做:

bytes('\\xeb\\x4d', 'utf-8')

我明白了:

b'\\xeb\\x4d'

我需要做以下事情:

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

【问题讨论】:

  • 您输入的是'\\xeb\\x4d' 还是'\xeb\x4d'?您在问题的正文中同时使用两者。
  • 我的输入是'\\xeb\\x4d'。我相应地编辑了我的问题。很抱歉造成混乱,感谢您的提醒。

标签: string python-3.x encoding byte


【解决方案1】:
>>> 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

请注意,latin1 是 Unicode 的前 256 个代码点,因此对 Unicode 的前 256 个字节进行编码会得到与原始代码点相同的字节值。

【讨论】:

  • 感谢马克的回答。关于 latin1 编解码器的解释帮助我理解了到底发生了什么!
【解决方案2】:
a = '\\xeb\\x4d'
a = bytes(a, 'utf-8')
a = a.decode('unicode_escape').encode('latin1')

给予

b'\xebM'

因为

'\x4d' == 'M'

【讨论】:

  • 可以直接用latin1,'\xeb\x4d'.encode('latin1')编码
  • 我的原始字符串已经转义了反斜杠,这就是为什么我需要使用 'unicode_escape' 编解码器进行解码。
猜你喜欢
  • 2022-01-11
  • 1970-01-01
  • 2019-06-26
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 2022-01-18
相关资源
最近更新 更多