r/learnpython • u/anonymous-fs • Aug 09 '25
What is the purpose of the format specifier "d"?
When using the format specifier "d" within an f-string, you can only input integers. I've seen online that the utility of "d" is to convert a number into a string of decimal digits, but if the specifier can only handle ints, what is it actually doing? For everything ChatGPT says it does, I have inputted the example into Python without the "d", and all outputs remained exactly the same.
21
u/mriswithe Aug 09 '25
Reference: https://docs.python.org/3/library/string.html#format-string-syntax
d outputs it in decimal or base 10 format as opposed to
o for octal
b for binary
4
u/Kriemhilt Aug 09 '25
Since base 10 is the default, it's probably fair to say that having the
dtype for integers isn't very useful, except for symmetry with the other bases, and for consistency withprintfand other formatters.4
u/mriswithe Aug 09 '25
In most cases yes I would agree. Usually the purpose of something like this is for completeness/edge cases/custom objects that might return differently for use case specific things.
2
2
u/JorgiEagle Aug 10 '25
Unless your input isn’t in base 10, and you don’t need it to be a base 10 integer, but printing it for debugging purposes is more helpful if it is in base 10
1
u/Kriemhilt Aug 10 '25
I don't think you understand what bases are.
Bases are only ways of representing numbers. They're only relevant when parsing or formatting.
Your values are almost certainly stored as binary, but that's not the default base for either parsing or formatting them.
1
u/QultrosSanhattan Aug 10 '25
Since note of those "read the docs" made-in-stackoverflow answers solved you question. I'll give you an LLM answer that actually works:
Alright, let me break down what d does in Python’s f-strings:
The
dstands for decimal integer.It tells Python: “Format this value as an integer in base 10.”
It only works with integers — if you give it a float or string, Python will throw an error.
Using
:dis explicit — it says: “show this number as a decimal integer”.Without it, Python usually defaults to decimal for integers anyway, so visually you often won’t see a difference.
But with
d, you enforce that the value must be an integer and formatted in decimal.
98
u/zanfar Aug 09 '25
Stop using other people's guesses. This is a straightforward "how does Python work" question, and you should immediately be looking at the documentation, which exists for exactly this reason.
In addition to the above, it's ensuring that an
intis provided.That's not actually testing anything relevant. You're just asking Python to format as it pleases. Very bluntly, you can't test what
ddoes by not usingd.I'm guessing you didn't try any of the other integer literal formats, did you?
Compare what happens when you use the following integers (with
d)?2147483647
0o177
0b100110111
0xdeadbeef
100_000_000_000
0b_1110_0101