Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有可变数字计数的Python格式_Python_Formatting_Format_Number Formatting - Fatal编程技术网

具有可变数字计数的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'
>>>