print()

Dave Angel davea at ieee.org
Sat Oct 17 10:02:27 EDT 2009


mattia wrote:
> Il Fri, 16 Oct 2009 21:04:08 +0000, mattia ha scritto:
>
>   
>> Is there a way to print to an unbuffered output (like stdout)? I've seen
>> that something like sys.stdout.write("hello") works but it also prints
>> the number of characters!
>>     
>
> 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)
>
> Thanks, Mattia
>
>   
Just as sys.stdout.write() is preferable to print() for your previous 
question, understanding str.format() is important to having good control 
over what your output looks like.  It's certainly not the only way, but 
the docs seem to say it's the preferred way in version 3.x    It was 
introduced in 2.6, so there are other approaches you might want if you 
need to work in 2.5 or earlier.

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

A brief explanation of the format string {3:07.2f}  is as follows:
    3 selects argument 3 of the function, which is x
    0 means to zero-fill the value after conversion
    7 means 7 characters total width  (this helps determine who many 
zeroes are inserted)
    2 means 2 digits after the decimal
    f  means fixed point format

You can generally leave out the parts you don't need, but this gives you 
lots of control over what things should look like.  There are lots of 
other parts,  but this is most of what you might need for controlled 
printing of floats.

The only difference from what you asked is that this rounds, where you 
seemed (!) to be asking for truncation of the extra columns.  If you 
really need to truncate, I'd recommend using str() to get a string, then 
use index() to locate the decimal separator, and then slice it yourself.

DaveA



More information about the Python-list mailing list