python 用 00 对每个字符进行十六进制填充

python encode hex pad every character with 00

对于要转换为十六进制的字符串,我需要用 00 填充每个字符。在 python 2.5.2 中有什么方法可以做到这一点吗?

例如

hextext = "H:\myfilepath.myfileending"
encodedhex = str(hextext.encode('hex'))
print encodedhex

当前打印

483a5c6d7966696c65706174682e6d7966696c65656e64696e67

但它应该打印

48003a005c00 etc.

此外,我希望所有字符都是大写 - 有什么办法可以做到这一点吗?

我也想知道为什么十六进制有时会以这种方式用 00 填充?

最简单的方法是

>>> hextext = "H:\myfilepath.myfileending"
>>> encodedhex = "".join(c.encode("hex")+"00" for c in hextext)
>>> encodedhex
'48003a005c006d007900660069006c00650070006100740068002e006d007900660069006c00650065006e00640069006e006700'
>>> encodedhex.upper()
'48003A005C006D007900660069006C00650070006100740068002E006D007900660069006C00650065006E00640069006E006700'

但是您确定要此输出而不是 UTF-16 编码的字符串吗?

>>> hextext.encode("utf-16-le")
'H\x00:\x00\\x00m\x00y\x00f\x00i\x00l\x00e\x00p\x00a\x00t\x00h\x00.\x00m\x00y\x00f\x00i\x00l\x00e\x00e\x00n\x00d\x00i\x00n\x00g\x00'