Python:在十六进制中打印一个变量 [英] Python: print a variable in hex

查看:133
本文介绍了Python:在十六进制中打印一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种在十六进制中打印字符串的方法。例如,我有这个字符串,然后转换为它的十六进制值。

  my_string =deadbeef
my_hex = my_string.decode('hex')

如何打印 my_hex as 0xde 0xad 0xbe 0xef

为了让我的问题变得清晰...假设我有一些数据,比如 0x01,0x02,0x03,0x04 存储在一个变量中。现在我需要用十六进制打印它,以便我可以读取它。我想我正在寻找一个python相当于 printf(%02x,my_hex)。我知道有 print'{0:x}'.format()但这不适用于 my_hex 它也不会填零。

你的意思是你有一串字节 my_hex 中你想以十六进制数字打印出来,对吗?例如,从你的例子:

 >>> my_string =deadbeef
>>> my_hex = my_string.decode('hex')#python 2 only
>>>打印my_hex

以下是一种方法:

 >>> print.join(my_hex中的n(hex(ord(n)))
0xde 0xad 0xbe 0xef

理解将字符串分解为字节, ord()将每个字节转换为相应的整数,并且 hex()格式化从 0x ## 中的每个整数。然后我们在两者之间添加空格。



额外奖励:如果您对unicode字符串使用此方法,则理解将为您提供unicode字符(不是字节),您将获得即使它们大于两位数,也是适当的十六进制值。


I'm trying to find a way to print a string in hex. For example I have this string which I then convert to its hex value.

my_string = "deadbeef"
my_hex = my_string.decode('hex')

How can I print my_hex as 0xde 0xad 0xbe 0xef? Thank you.

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 hex 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.

解决方案

You mean you have a string of bytes in my_hex which you want to print out as hex numbers, right? E.g., from your example:

>>> my_string = "deadbeef"
>>> my_hex = my_string.decode('hex')  # python 2 only
>>> print my_hex
Þ ­ ¾ ï

Here's one way to do it:

>>> print " ".join(hex(ord(n)) for n in my_hex)
0xde 0xad 0xbe 0xef

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.

Bonus: If you use this method with unicode 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:在十六进制中打印一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆