Python,打印十六进制会删除前0个吗? [英] Python , Printing Hex removes first 0?

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

问题描述

看看这个:

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

让我们说这段代码找到了十六进制的00 04 0f,而不是那样写,而是删除了第一个0并写为:04f 有帮助吗?

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?

推荐答案

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

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

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

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

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

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

这是代码中的样子:

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

这篇关于Python,打印十六进制会删除前0个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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