Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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' 
like image 285
harijay Avatar asked Apr 11 '11 21:04

harijay


People also ask

What is the string .format method used for in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

How do you use %d strings in Python?

The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.

What is format .2f ))?

A format of . 2f (note the f ) means to display the number with two digits after the decimal point. So the number 1 would display as 1.00 and the number 1.5555 would display as 1.56 .

What is %s %d %F in Python?

Answer. In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point.


2 Answers

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' 
like image 163
Justin Waugh Avatar answered Oct 07 '22 09:10

Justin Waugh


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.

like image 44
pajton Avatar answered Oct 07 '22 10:10

pajton