简体   繁体   中英

How to print voltages side by side?

I'm using a program that prints out voltages one right below the other, like:

2.333

2.334

2.336

2.445

But I want it like:

2.333 2.334 2.336 2.445 

Ok, here is what works for me:

while True:
   voltsdiff = adc.readADCDifferential01(4096, 8)
   import sys
   print '{:.4f}'.format(voltsdiff),
   sys.stdout.flush()

Just print them with a comma

print "%.4f" % (voltsdiff),

Moreover, you might want to use format method. You can read all about formatting here

print "{:.4f}".format(voltsdiff),

Lets say, you are printing these values by iterating a list, you can do something like this

data = [2.333, 2.334, 2.336, 2.445]
print " ".join(data)

If you print to terminal, you may use stdout with \\r or \\b escape

sys.stdout.write("\r%.4f\t%.4f\t%.4f\t%.4f" % (v1, v2, v3, v4))

The "\\r" escape move the cursor at begining of line (like cr on same line) and "\\b" is untab: move 4 position back.

PS:stdout do some cache, you should call sys.stdout.flush() to be sure that the result is on terminal at request, before the buffer is full

As others have answered, to print output without a newline in Python 2, put a comma at the end of your print statement:

print "%.4f" % voltsdiff,

However, this will not flush the output, as standard output is line buffered by default (it will only be flushed when a newline is added to the output). There are a few ways you can fix that.

First, you could, at some point, append a newline with just a basic print statement, eg:

for i, voltsdiffs in enumerate(many_voltages):
    print "%.4f" % voltsdiffs,
    if i % 10 == 9:
         print # puts a newline after every 10 values

Next, you could explicitly flush standard output, using sys.stdout.flush() :

print "%.4f" % voltsdiffs,
sys.stdout.flush()

Finally, you can use the Python 3 style print function, which has a flush parameter (which does the flushing for you, if it is True ):

# before any other code
from __future__ import print_function

# later
print(format(voltsdiffs, ".4f"), end=" ", flush=True)

I'd generally recommend the last version, as it's what you'll need to use in the future if you port your code to Python 3. It's also quite explicit, with each special characteristic of the printing (no newline at the end, flushing automatically) called for by a separate keyword argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM