How do we use the Python string formatters %d and %f?


#1

Question

How do we use the Python string formatters %d and %f?

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.

For example,

"print %d" % (3.78) 
# This would output 3

num1 = 5
num2 = 10
"%d + %d is equal to %d" % (num1, num2, num1 + num2)
# This would output 
# 5 + 10 is equal to 15

The %f formatter is used to input float values, or numbers with values after the decimal place. This formatter allows us to specify a number of decimal places to round the values by.

For example,

number = 3.1415
print "%f" % number
# You might see this output 3.1415000,
# due to how the float values are stored

print "%.3f" % number
# 3.142
# When specifying to a number of decimal places
# it will round up if the next digit value is >= 5