Python 2.7:% d,% s, and float ()

I am trying to teach myself a little coding through the book “learning python the hard way” and am struggling with% d /% s /% r when binding to displaying a floating point number. How to pass a floating point number to a format character? At first I tried% d, but my answers displayed as integers .... I had some success with% r, but I was on the assumption that it was usually reserved for debugging? I realized that for separation in python 2.x, you need to manually float the denominator so that it works correctly for some reason.

Code example:

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) 
+7
source share
2 answers

Try the following:

 print "First is: %f" % (first) print "Second is: %f" % (second) 

I am not sure what the answer is. But other than that it will be:

 print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans) 

There is a lot of text in the formatting of string specifiers. You can use it and get a list of qualifiers. One thing I forgot to mention:

If you try this:

 print "First is: %s" % (first) 

It converts the float value first to a string. So it will work too.

+3
source

See String Formatting Operations :

%d is the format code for an integer. %f is the format code for float.

%s prints str() object (what you see when you print(object) ).

%r prints the repr() object (what you see when you print(repr(object)) .

For float% s,% r and% f, all display the same value, but this does not apply to all objects. Other fields of the format specifier work differently:

 >>> 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 
+13
source

All Articles