具有可变数字计数的Python格式
因此,我可以做到:具有可变数字计数的Python格式,python,formatting,format,number-formatting,Python,Formatting,Format,Number Formatting,因此,我可以做到: >>> '%.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 conve
>>> '%.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
>>数字=4
>>>'%.'+str(数字)+'x'%0x45f
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:在字符串格式化过程中并非所有参数都已转换
运算符%
的优先级高于+
,因此需要将第一部分放在括号中:
>>> digits = 4
>>> ('%.'+str(digits)+'x') % 0x45f
'045f'
>>>
否则,将首先计算'x'%0x45f
但是,现代方法是用于字符串格式化操作:
>>> digits = 4
>>> "{:0{}x}".format(0x45f, digits)
'045f'
>>>