<p>根据文档,<a href="https://docs.python.org/3/library/functions.html#hex" rel="nofollow">^{<cd1>}</a>将<em>“一个整数转换为前缀为'0x'</em>”的小写十六进制字符串,因此当使用<code>hex()</code>时,总是会得到一个<code>0x</code>前缀。如果您想连接多个十六进制表示,则必须删除它。在</p>
<blockquote>
<p>But sometimes the byte string has a <code>0</code> next to a <code>x</code> and it gets removed from the string resulting in a incorrect hexadecimal string. (the string above is missing the <code>0</code> at the beginning).</p>
</blockquote>
<p>那没有任何意义。<code>x</code>不是有效的十六进制字符,因此在您的解决方案中,它只能由<code>hex()</code>调用生成<em>。如上所述,这将始终创建一个<code>0x</code>。因此序列<code>0x</code>在结果字符串中不会以不同的方式出现,因此用任何内容替换{<cd3>}应该可以很好地工作。在</p>
<p>您的解决方案中的实际问题是<code>hex()</code>没有执行两位数的结果,如下面的示例所示:</p>
<pre><code>>>> hex(10)
'0xa'
>>> hex(2)
'0x2'
</code></pre>
<p>所以在您的例子中,由于字符串以<code>b\x06</code>开头,它代表数字<code>6</code>,<code>hex(6)</code>只返回{<cd13>},所以这里只得到一个数字,这才是问题的真正原因。在</p>
<hr/>
<p>您可以使用格式字符串执行到十六进制的转换。这样,你就可以省去前缀,并强制使用两位数的长度。然后您可以使用<code>str.join</code>将其组合成一个十六进制字符串:</p>
^{pr2}$
<p>此解决方案不仅适用于字节字符串,而且适用于任何可以格式化为十六进制字符串(例如整数列表)的内容:</p>
<pre><code>>>> value = [1, 2, 3, 4]
>>> ''.join(['{:02x}'.format(x) for x in value])
'01020304'
</code></pre>