16

OK I was looking into number formatting and I found that you could use %d or %i to format an integer. For example:

number = 8
print "your number is %i." % number

or

number = 8
print "your number is %d." % number

But what is the difference? I mean i found something but it was total jibberish. Anyone speak Mild-Code or English here?

6
  • 1
    Python uses the C conventions here, the same answer applies. Commented Jul 16, 2013 at 15:06
  • If you ever want to upgrade to python 3, I recommend getting into the habit of using parens around the print body, since print is a function in python 3. Commented Jul 16, 2013 at 15:09
  • @MartijnPieters I don't really understand that though. I was looking a bit for more English lol Commented Jul 16, 2013 at 15:12
  • RTFM on format specifiers. They're the same. What part of "signed integer decimal" don't you understand? Commented Jul 16, 2013 at 15:13
  • @malcolmk181: sure, an english language explanation is added below. Commented Jul 16, 2013 at 15:15

3 Answers 3

22

Python copied the C formatting instructions.

For output, %i and %d are the exact same thing, both in Python and in C.

The difference lies in what these do when you use them to parse input, in C by using the scanf() function. See Difference between format specifiers %i and %d in printf.

Python doesn't have a scanf equivalent, but the Python string formatting operations retained the two options to remain compatible with C.

The new str.format() and format() format specification mini-language dropped support for i and stuck with d only.

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

4 Comments

OK thanks, that's a bit easier to understand :)
The new format specification mini-language may have dropped i, but it added n, which is almost as the same as i except it's locale-aware number separator-wise.
@martineau: Which means it is not the same thing as d. i is the same as d.
@Martijn: Sorry, my mistake, I meant to say "n is almost the same as d except...".
3

No difference.

And here's the proof.

The reason why there are two is that, %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.

2 Comments

@malcolmk i have answered and reasoned why there are 2 choices
Seems reasonable, but we'll never know for sure since it would require the ability to read minds in the past...
2

There isn't any, see the Python String Formatting Manual: http://docs.python.org/2/library/stdtypes.html#string-formatting

2 Comments

There's gotta be a reason though right?
The string output formatting in Python is obviously inspired by C. Martijn Pieters pointed you in the right direction already: Difference between format specifiers %i and %d in printf