问题
If I understood the docs correctly, in python 2.6.5 string formatting "{0:d}" would do the same as "%d" with the String.format() way of formatting strings
" I have {0:d} dollars on me ".format(100.113)
Should print "I have 100 dollars on me "
However I get the error :
ValueError: Unknown format code 'd' for object of type 'float'
The other format operations do work.for eg.
>>> "{0:e}".format(112121.2111)
'1.121212e+05'
回答1:
That error is signifying that you are passing a float to the format code expecting an integer.
Use {0:f}
instead. Thus:
"I have {0:f} dollars on me".format(100.113)
will give:
'I have 100.113000 dollars on me'
回答2:
Yes, you understand correctly. However you are passing float
(i.e. 100.113
), not int
. Either convert it to int
: int(100.113)
or just pass 100
.
回答3:
delete 'd', since the object type might not be a number as in my case
来源:https://stackoverflow.com/questions/5627605/string-formatting-with-0d-format-gives-unknown-format-code-d-for-object-o