【问题标题】:Python format with variable digits count具有可变位数计数的 Python 格式
【发布时间】:2014-05-27 14:03:51
【问题描述】:

所以,我可以这样做:

>>> '%.4x' % 0x45f
'045f'

但我需要从变量中传递 4,smth 之类的

>>> digits=4
>>> '%.'+str(digits)+'x' % 0x45f
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

【问题讨论】:

    标签: python formatting format number-formatting


    【解决方案1】:

    % 运算符的优先级高于+,因此需要将第一部分放在括号中:

    >>> digits = 4
    >>> ('%.'+str(digits)+'x') % 0x45f
    '045f'
    >>>
    

    否则,'x' % 0x45f 将首先被评估。


    但是,现代方法是使用str.format 进行字符串格式化操作:

    >>> digits = 4
    >>> "{:0{}x}".format(0x45f, digits)
    '045f'
    >>>
    

    【讨论】:

      猜你喜欢
      • 2011-03-14
      • 2012-06-26
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多