15

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Python uses the C conventions here, the same answer applies. – Martijn Pieters Jul 16 '13 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. – beatgammit Jul 16 '13 at 15:09
  • @MartijnPieters I don't really understand that though. I was looking a bit for more English lol –  Jul 16 '13 at 15:12
  • RTFM on format specifiers. They're the same. What part of "signed integer decimal" don't you understand? – martineau Jul 16 '13 at 15:13
  • @malcolmk181: sure, an english language explanation is added below. – Martijn Pieters Jul 16 '13 at 15:15
  • not really a duplicate this is a question about python the one marked as identical is explicitly a c++ question. sometimes stack overflow is weird. – eric Apr 21 '19 at 15:53

3 Answers3

21

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.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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.

tenstar
  • 9,816
  • 9
  • 24
  • 45
2

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

Sven
  • 1,748
  • 1
  • 14
  • 14
  • There's gotta be a reason though right? –  Jul 16 '13 at 15:14
  • 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](http://stackoverflow.com/questions/1893490/difference-between-format-specifiers-i-and-d-in-printf) – Sven Jul 16 '13 at 15:19