Python将字节字符串转换为字节数组

时间:2018-08-08 20:00:38

标签: python character-encoding bytestring

例如,给定任意字符串。可以是chars,也可以是随机的bytes

string = '\xf0\x9f\xa4\xb1'

我要输出:

b'\xf0\x9f\xa4\xb1'

这似乎很简单,但是我在任何地方都找不到答案。当然,只需在字符串后键入b即可。但我想执行此运行时,或者从包含字节字符串的变量中执行。

如果给定的stringAAAA或某些已知的characters,我可以简单地做string.encode('utf-8'),但是我希望字节字符串只是随机的。对'\xf0\x9f\xa4\xb1'(随机字节)执行此操作会产生意外结果b'\xc3\xb0\xc2\x9f\xc2\xa4\xc2\xb1'

必须有一种更简单的方法吗?

编辑:

我想在不使用编码的情况下将字符串转换为字节

2 个答案:

答案 0 :(得分:3)

Latin-1 字符编码很简单(与 Python 支持的所有其他编码不同)将 0x00-0xff 范围内的每个代码点编码为具有相同值的字节。

<xsl:template name="replace-string">
<xsl:param name="text"/>
<xsl:param name="replace"/>
<xsl:param name="with"/>
<xsl:choose>
  <xsl:when test="contains($text,$replace)">
    <xsl:value-of select="substring-before($text,$replace)"/>
    <xsl:value-of select="$with"/>
    <xsl:call-template name="replace-string">
      <xsl:with-param name="text"
        select="substring-after($text,$replace)"/>
      <xsl:with-param name="replace" select="$replace"/>
      <xsl:with-param name="with" select="$with"/>
    </xsl:call-template>
  </xsl:when>
  <xsl:otherwise>
    <xsl:value-of select="$text"/>
  </xsl:otherwise>
</xsl:choose>

你说你不想使用编码,但避免它的替代方法似乎差很多。

UTF-8 编码是不合适的,因为正如您已经发现的,0x7f 以上的代码点映射到多个字节(最多四个字节)的序列,其中没有一个完全是作为字节值的输入代码点。

省略 byteobj = '\xf0\x9f\xa4\xb1'.encode('latin-1') 的参数(如现在已删除的答案中)会强制 Python 猜测编码,这会产生依赖于系统的行为(可能在大多数系统上选择 UTF-8,除了 Windows,它通常会取而代之的是选择更不可预测,通常更险恶和可怕的东西)。

答案 1 :(得分:0)

我找到了可行的解决方案

import struct

def convert_string_to_bytes(string):
    bytes = b''
    for i in string:
        bytes += struct.pack("B", ord(i))
    return bytes       

string = '\xf0\x9f\xa4\xb1'

print (convert_string_to_bytes(string))

输出: b'\xf0\x9f\xa4\xb1'

相关问题