1

So, I can do:

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

But I need to pass 4 from variable, smth like

>>> 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

1 Answer 1

2

The % operator has a higher precedence than +, so you need to put the first part in parenthesis:

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

Otherwise, 'x' % 0x45f will be evaluated first.


However, the modern approach is to use str.format for string formatting operations:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.