[英]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
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. 此外,您可能要使用format
方法。 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 如果打印到终端,则可以将stdout与\\ r或\\ b转义一起使用
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. “ \\ r”转义符将光标移动到行首(如cr在同一行上),而“ \\ b”则取消制表符:向后移4位。
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 PS:stdout做一些缓存,您应该在缓冲区已满之前调用sys.stdout.flush()以确保结果在请求时显示在终端上
As others have answered, to print output without a newline in Python 2, put a comma at the end of your print statement: 正如其他人回答的那样,要在Python 2中打印输出时不带换行符,请在打印语句的末尾添加一个逗号:
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: 首先,您可以在某个时候在换行符后面附加一个基本的print
语句,例如:
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()
: 接下来,您可以使用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
): 最后,您可以使用Python 3样式的print
函数,该函数具有flush
参数(如果为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. 我通常会建议使用最后一个版本,因为如果您将代码移植到Python 3,这是将来需要使用的版本。它也非常明确,具有打印的每个特殊特征(末尾没有换行符,刷新自动)由单独的关键字参数调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.