4

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'

Sam
  • 141
  • 1
  • 2
  • 9
  • 1
    https://stackoverflow.com/questions/22617/format-numbers-to-strings-in-python might have the answer for you. – Stef van der Zon Dec 17 '18 at 10:25
  • See also: https://stackoverflow.com/questions/4148790/lazy-logger-message-string-evaluation – you might be better off not doing the formatting yourself. – mkrieger1 Dec 17 '18 at 10:35
  • And `"%d".format(value)` should not even work properly. It should be either `"%d" % value"` or `"{:d}".format(value)"` (or simply `"{}".format(value)`). – mkrieger1 Dec 17 '18 at 10:36
  • Possible duplicate of [What is the difference between %i and %d in Python?](https://stackoverflow.com/questions/17680256/what-is-the-difference-between-i-and-d-in-python) – mkrieger1 Dec 17 '18 at 10:38

3 Answers3

2

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.

L3viathan
  • 26,748
  • 2
  • 58
  • 81
2

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

Frida Schenker
  • 1,219
  • 1
  • 9
  • 14
0

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