如何在没有换行符或空格的情况下打印 [英] How to print without a newline or space
问题描述
我想用 Python 来做.我想在这个例子中用 C 做什么:
I'd like to do it in Python. What I'd like to do in this example in C:
#include <stdio.h>
int main() {
int i;
for (i=0; i<10; i++) printf(".");
return 0;
}
输出:
..........
在 Python 中:
In Python:
>>> for i in range(10): print('.')
.
.
.
.
.
.
.
.
.
.
>>> print('.', '.', '.', '.', '.', '.', '.', '.', '.', '.')
. . . . . . . . . .
在 Python 中,print
会添加一个
或空格.我怎样才能避免这种情况?我想知道如何附加"字符串到 stdout
.
In Python, print
will add a
or space. How can I avoid that? I'd like to know how to "append" strings to stdout
.
推荐答案
在 Python 3 中,您可以使用 sep= 和 end=
参数="https://docs.python.org/library/functions.html#print" rel="noreferrer">print
函数:
In Python 3, you can use the sep=
and end=
parameters of the print
function:
不要在字符串末尾添加换行符:
To not add a newline to the end of the string:
print('.', end='')
不要在要打印的所有函数参数之间添加空格:
To not add a space between all the function arguments you want to print:
print('a', 'b', 'c', sep='')
您可以将任何字符串传递给任一参数,并且可以同时使用这两个参数.
You can pass any string to either parameter, and you can use both parameters at the same time.
如果您在缓冲时遇到问题,可以通过添加 flush=True
关键字参数来刷新输出:
If you are having trouble with buffering, you can flush the output by adding flush=True
keyword argument:
print('.', end='', flush=True)
Python 2.6 和 2.7
从 Python 2.6 开始,您可以使用 print 函数"noreferrer">__future__
模块:
Python 2.6 and 2.7
From Python 2.6 you can either import the print
function from Python 3 using the __future__
module:
from __future__ import print_function
它允许您使用上面的 Python 3 解决方案.
which allows you to use the Python 3 solution above.
但是,请注意 flush
关键字在 Python 2 中从 __future__
导入的 print
函数版本中不可用;它仅适用于 Python 3,更具体地说是 3.3 及更高版本.在早期版本中,您仍然需要通过调用 sys.stdout.flush()
手动刷新.您还必须在执行此导入的文件中重写所有其他打印语句.
However, note that the flush
keyword is not available in the version of the print
function imported from __future__
in Python 2; it only works in Python 3, more specifically 3.3 and later. In earlier versions you'll still need to flush manually with a call to sys.stdout.flush()
. You'll also have to rewrite all other print statements in the file where you do this import.
或者你可以使用 sys.stdout.write()代码>
Or you can use sys.stdout.write()
import sys
sys.stdout.write('.')
您可能还需要致电
sys.stdout.flush()
确保立即刷新 stdout
.
这篇关于如何在没有换行符或空格的情况下打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!