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

后端 未结 3 983
独厮守ぢ
独厮守ぢ 2020-12-17 09:02

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



        
相关标签:
3条回答
  • 2020-12-17 09:20

    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'
    
    0 讨论(0)
  • 2020-12-17 09:27

    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.

    0 讨论(0)
  • 2020-12-17 09:43

    delete 'd', since the object type might not be a number as in my case

    0 讨论(0)
提交回复
热议问题