装饰十六进制功能以填充零 [英] Decorating Hex function to pad zeros

查看:91
本文介绍了装饰十六进制功能以填充零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个简单的函数:

def padded_hex(i, l):
    given_int = i
    given_len = l

    hex_result = hex(given_int)[2:] # remove '0x' from beginning of str
    num_hex_chars = len(hex_result)
    extra_zeros = '0' * (given_len - num_hex_chars) # may not get used..

    return ('0x' + hex_result if num_hex_chars == given_len else
            '?' * given_len if num_hex_chars > given_len else
            '0x' + extra_zeros + hex_result if num_hex_chars < given_len else
            None)

示例:

padded_hex(42,4) # result '0x002a'
hex(15) # result '0xf'
padded_hex(15,1) # result '0xf'

虽然这对我来说很清楚,并且适合我的用例(用于简单打印机的简单测试工具),但我不禁认为还有很多改进的余地,并且可以将其缩小为非常简洁的内容. /p>

还有什么其他方法可以解决这个问题?

解决方案

使用新的

说明:

{   # Format identifier
0:  # first parameter
#   # use "0x" prefix
0   # fill with zeroes
{1} # to a length of n characters (including 0x), defined by the second parameter
x   # hexadecimal number, using lowercase letters for a-f
}   # End of format identifier

如果您希望字母十六进制数字为大写字母,但前缀为小写字母"x",则需要采取一些变通方法:

>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'

从Python 3.6开始,您还可以执行以下操作:

>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'

I wrote this simple function:

def padded_hex(i, l):
    given_int = i
    given_len = l

    hex_result = hex(given_int)[2:] # remove '0x' from beginning of str
    num_hex_chars = len(hex_result)
    extra_zeros = '0' * (given_len - num_hex_chars) # may not get used..

    return ('0x' + hex_result if num_hex_chars == given_len else
            '?' * given_len if num_hex_chars > given_len else
            '0x' + extra_zeros + hex_result if num_hex_chars < given_len else
            None)

Examples:

padded_hex(42,4) # result '0x002a'
hex(15) # result '0xf'
padded_hex(15,1) # result '0xf'

Whilst this is clear enough for me and fits my use case (a simple test tool for a simple printer) I can't help thinking there's a lot of room for improvement and this could be squashed down to something very concise.

What other approaches are there to this problem?

解决方案

Use the new .format() string method:

>>> "{0:#0{1}x}".format(42,6)
'0x002a'

Explanation:

{   # Format identifier
0:  # first parameter
#   # use "0x" prefix
0   # fill with zeroes
{1} # to a length of n characters (including 0x), defined by the second parameter
x   # hexadecimal number, using lowercase letters for a-f
}   # End of format identifier

If you want the letter hex digits uppercase but the prefix with a lowercase 'x', you'll need a slight workaround:

>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'

Starting with Python 3.6, you can also do this:

>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'

这篇关于装饰十六进制功能以填充零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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