5

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'

4

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wrong, see my answwer.
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

1 Comment

"for printf or logging, %i and %d are actually same thing" -> wrong, see my answer
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.