String Formatting in Python %i

Viewed 2009

I have to convert a code from Python2.x to Python3 (mostly string format) I came across something like this:

Logger.info("random String %d and %i".format(value1, value2))

Now, I know %d can be replaced with {:d} but could not find equivalent of %i (Signed) using {:i} gives the following error:

ValueError: Unknown format code 'i' for object of type 'int'

3 Answers

In Python there is no difference between %d and %i, so you can translate them the same way. %i only exists for compatibility with other languages' printf functions.

The short answer: Python3 str.format() specification has dropped the support for "i" (%i or {:i}). It only uses "d" (%d or {:d}) for specifiying integers. Therefore, you can simply use {:d} for all integers.

The long answer: For output, i.e. for printf or logging, %i and %d are actually same thing, both in Python and in C. There is a difference but only when you use them to parse input, like with scanf(). For scanf, %d and %i actually both mean signed integer but %i inteprets the input as a hexadecimal number if preceded by 0x and octal if preceded by 0 and otherwise interprets the input as decimal. Therefore, for normal use, it is always better to use %d, unless you want to specify input as hexadecimal or octal.

For more details, please take a look at the format specification here: https://docs.python.org/2/library/string.html#formatspec

%i is just an alternative to %d ,if you want to look at it at a high level (from python point of view).

Here's what python.org has to say about %i: Signed integer decimal.

And %d: Signed integer decimal.

%d stands for decimal and %i for integer.

but both are same, you can use both.

so you can translate them the same way.

Related