print()

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Oct 18 18:04:11 EDT 2009


En Sun, 18 Oct 2009 10:35:34 -0200, mattia <gervaz at gmail.com> escribió:

> Il Sat, 17 Oct 2009 10:02:27 -0400, Dave Angel ha scritto:
>> mattia wrote:
>>> Il Fri, 16 Oct 2009 21:04:08 +0000, mattia ha scritto:
>>>
>>> Another question (always py3). How can I print only the first number
>>> after the comma of a division?
>>> e.g. print(8/3) --> 2.66666666667
>>> I just want 2.6 (or 2.66)
>>>
>> x = 8/3
>> dummy0=dummy1=dummy2=42
>> s = "The answer is approx. {3:07.2f} after rounding".format(dummy0,
>> dummy1, dummy2, x)
>> print(s)
>>
>> will print out the following:
>>
>> The answer is approx. 0002.67 after rounding
>
> Yes, reading the doc I've come up with
> s = "%(0)03.02f%(1)s done" % {"0": 100.0-100.0*(size/tot), "1": "%"}
> but to it is not a good idea to use a dict here..

No need for a dict, you could use instead:

s = "%03.02f%s done" % (100.0-100.0*(size/tot), "%")

or (%% is the way to embed a single %):

s = "%03.02f%% done" % (100.0-100.0*(size/tot),)

or even:

s = "%03.02f%% done" % (100.0-100.0*(size/tot))

but the new str.format() originally suggested by Dave Angel is better:

s = "{0:03.02f}% done".format(100.0-100.0*(size/tot))

(BTW, why 03.02f? The output will always have at least 4 chars, so 03  
doesn't mean anything... Maybe you want {0:06.2f} (three places before the  
decimal point, two after it, filled with 0's on the left)?)

-- 
Gabriel Genellina




More information about the Python-list mailing list