I am attempting to teach myself a little coding through the "learn python the hard way" book and am struggling with %d / %s / %r when tying to display a floating point number. How do you properly pass a floating point number with a format character? First I tried %d but that made my answers display as integers.... I had some success with %r, but I was under the assumption that was usually reserved for debugging? I figured out for division in python 2.x you have to manually float the denominator for it to properly work for some reason.
Example code:
def divide (a, b):
print "WE DIVIDING %r and %r NOW" % (a, b)
return a / float(b)
print "Input first number:"
first = float(raw_input("> "))
print "OK, now input second number:"
second = float(raw_input("> "))
ans = divide(first, second)
print "DONE: %r DIVIDED BY %r EQUALS %r, SWEET MATH BRO!" % (first, second, ans)
This question is related to
python
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
Source: Stackoverflow.com