【问题标题】:Decorating Hex function to pad zeros装饰十六进制函数以填充零
【发布时间】:2012-09-20 05:51:29
【问题描述】:

我写了这个简单的函数:

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'

虽然这对我来说足够清楚并且适合我的用例(用于简单打印机的简单测试工具),但我不禁认为还有很大的改进空间,这可以压缩成非常简洁的东西。

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

【问题讨论】:

    标签: python hex padding built-in


    【解决方案1】:

    使用新的.format()字符串方法:

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

    说明:

    {   # 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'
    

    【讨论】:

    • 是否可以在 python 3.6 中将其写为格式字符串?
    • 是的,但没有任何成功,因为我无法找出正确的语法:value = 42; padding = 6; f"{value:#0{padding}x}" 抛出语法错误:` File "", line 1 f"{value:# 0{padding}x}" ^ SyntaxError: 无效语法`
    • 这适用于我在 Python 3.6.4 上。尝试import sys; print(sys.version) 以确保您运行的是正确的解释器。
    • python 真的很喜欢把事情复杂化
    • @Katu:你可以做f"{value:#0{padding}X}".replace("X","x")
    【解决方案2】:

    这个怎么样:

    print '0x%04x' % 42
    

    【讨论】:

    • 使用*传递宽度:'0x%0*x' % (4,42)
    【解决方案3】:

    如果只是为了前导零,你可以试试zfill函数。

    '0x' + hex(42)[2:].zfill(4) #'0x002a'
    

    【讨论】:

      【解决方案4】:
      "{:02x}".format(7)   # '07'
      "{:02x}".format(27)  # '1b'
      

      在哪里

      • :formatting specification 第一个参数{}.format() 的开始
      • 02 表示“用0s 将输入从左侧填充到长度2
      • x 表示“格式为带有小写字母的十六进制”

      您也可以使用f-strings

      f"{7:02x}"   # '07'
      f"{27:02x}"  # '1b'
      

      【讨论】:

        【解决方案5】:

        使用* 传递宽度,X 传递大写

        print '0x%0*X' % (4,42) # '0x002A'
        

        根据georgAshwini Chaudhary 的建议

        【讨论】:

        • 为什么要用*来传递宽度?
        • @RafaelJ 使其通用,而不是硬编码
        【解决方案6】:

        假设你想为十六进制数字添加前导零,例如你想要 7 位数字,你的十六进制数字应该写在上面,你可以这样做:

        hexnum = 0xfff
        str_hex =  hex(hexnum).rstrip("L").lstrip("0x") or "0"
        '0'* (7 - len(str_hexnum)) + str_hexnum
        

        结果如下:

        '0000fff'
        

        【讨论】:

        • '%0*x' % (7,0xfff)
        【解决方案7】:

        没有一个答案能很好地处理负数...
        试试这个:

        val = 42
        nbits = 16
        '{:04X}'.format(val & ((1 << nbits)-1))
        

        【讨论】:

        • '{:0{}X}'.format(val &amp; ((1 &lt;&lt; nbits)-1), int((nbits+3)/4)) 将正确设置宽度。
        猜你喜欢
        • 1970-01-01
        • 2014-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-02
        • 2019-03-01
        • 2016-07-31
        • 2021-06-04
        相关资源
        最近更新 更多