在Python中以十六进制打印变量 [英] Print a variable in hexadecimal in Python
问题描述
我正在尝试找到一种以十六进制打印字符串的方法.例如,我有这个字符串,然后将其转换为十六进制值.
I'm trying to find a way to print a string in hexadecimal. For example, I have this string which I then convert to its hexadecimal value.
my_string = "deadbeef"
my_hex = my_string.decode('hex')
如何将my_hex
打印为0xde 0xad 0xbe 0xef
?
为了使我的问题更清楚...假设我有一些像0x01, 0x02, 0x03, 0x04
这样的数据存储在一个变量中.现在,我需要以十六进制打印它,以便可以读取它.我想我正在寻找与printf("%02x", my_hex)
等效的Python.我知道有print '{0:x}'.format()
,但是不能与my_hex
一起使用,也不会用零填充.
To make my question clear... Let's say I have some data like 0x01, 0x02, 0x03, 0x04
stored in a variable. Now I need to print it in hexadecimal so that I can read it. I guess I am looking for a Python equivalent of printf("%02x", my_hex)
. I know there is print '{0:x}'.format()
, but that won't work with my_hex
and it also won't pad with zeroes.
推荐答案
您的意思是您想在my_hex
中包含一个 bytes 字符串,您希望将其打印为十六进制数字,对吗?例如,让我们举个例子:
You mean you have a string of bytes in my_hex
which you want to print out as hex numbers, right? E.g., let's take your example:
>>> my_string = "deadbeef"
>>> my_hex = my_string.decode('hex') # python 2 only
>>> print my_hex
Þ ¾ ï
此构造仅适用于Python 2;但是您可以在Python 2或Python 3中编写与文字相同的字符串,如下所示:
This construction only works on Python 2; but you could write the same string as a literal, in either Python 2 or Python 3, like this:
my_hex = "\xde\xad\xbe\xef"
那么,答案就来了.这是将字节打印为十六进制整数的一种方法:
So, to the answer. Here's one way to print the bytes as hex integers:
>>> print " ".join(hex(ord(n)) for n in my_hex)
0xde 0xad 0xbe 0xef
理解将字符串分解为字节,ord()
将每个字节转换为相应的整数,并且hex()
格式化0x##
中的每个整数.然后在它们之间添加空格.
The comprehension breaks the string into bytes, ord()
converts each byte to the corresponding integer, and hex()
formats each integer in the from 0x##
. Then we add spaces in between.
奖金:如果您将此方法与unicode字符串(或Python 3字符串)一起使用,则理解将为您提供unicode字符(而不是字节),即使它们大于两位数,您也将获得适当的十六进制值
Bonus: If you use this method with unicode strings (or Python 3 strings), the comprehension will give you unicode characters (not bytes), and you'll get the appropriate hex values even if they're larger than two digits.
在Python 3中,您更可能希望使用字节字符串来完成此操作;在这种情况下,理解已经返回整数,因此您必须省去ord()
部分,只需对它们调用hex()
即可:
In Python 3 it is more likely you'll want to do this with a byte string; in that case, the comprehension already returns ints, so you have to leave out the ord()
part and simply call hex()
on them:
>>> my_hex = b'\xde\xad\xbe\xef'
>>> print(" ".join(hex(n) for n in my_hex))
0xde 0xad 0xbe 0xef
这篇关于在Python中以十六进制打印变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!