String formatting with “{0:d}”.format gives Unknown format code 'd' for object of type 'float'

爱⌒轻易说出口 提交于 2019-12-05 10:26:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!