Python ,打印十六进制删除第一个 0?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15884677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:15:51  来源:igfitidea点击:

Python , Printing Hex removes first 0?

pythonhex

提问by thethiny

take a look at this:

看看这个:

fc = '0x'
for i in b[0x15c:0x15f]:
    fc += hex(ord(i))[2:]

Lets say this code found the hex 00 04 0f , instead of writing it that way , it removes the first 0 , and writes : 04f any help?

假设这段代码找到了十六进制 00 04 0f ,而不是那样写,它删除了第一个 0 ,并写道: 04f 有什么帮助吗?

采纳答案by Andrew Clark

This is happening because hex()will not include any leading zeros, for example:

发生这种情况是因为hex()不会包含任何前导零,例如:

>>> hex(15)[2:]
'f'

To make sure you always get two characters, you can use str.zfill()to add a leading zero when necessary:

为确保始终获得两个字符,您可以str.zfill()在必要时使用添加前导零:

>>> hex(15)[2:].zfill(2)
'0f'

Here is what it would look like in your code:

这是您的代码中的样子:

fc = '0x'
for i in b[0x15c:0x15f]:
    fc += hex(ord(i))[2:].zfill(2)

回答by Joran Beasley

print ["0x%02x"%ord(i) for i in b[0x15c:0x15f]]

use a format string "%2x"tells it to format it to be 2 characters wide, likewise "%02x"tells it to pad with 0's

使用格式字符串"%2x"告诉它格式化为 2 个字符宽,同样"%02x"告诉它用 0 填充

note that this would still remove the leading 0's from things with more than 2 hex values eg: "0x%02x"%0x0055 => "0x55"

请注意,这仍然会从具有超过 2 个十六进制值的事物中删除前导 0,例如: "0x%02x"%0x0055 => "0x55"

回答by Torxed

It's still just a graphical representation for your convenience.
The value is not actually stripped from the data, it's just visually shortened.

为了您的方便,它仍然只是一个图形表示。
该值实际上并未从数据中剥离,只是在视觉上缩短了。

Full description here and why it is or why it's not important: Why are hexadecimal numbers prefixed with 0x?

此处的完整说明以及为什么它不重要或为什么它不重要:为什么十六进制数字以 0x 为前缀?

回答by Senyai

>>> map("{:02x}".format, (10, 13, 15))
['0a', '0d', '0f']