如何在没有换行符或空格的情况下进行打印

如何在没有换行符或空格的情况下进行打印

本文介绍了如何在没有换行符或空格的情况下进行打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 python .在此示例中,我想在 c :

I'd like to do it in python. What I'd like to do in this example in c:

在C中:

#include <stdio.h>

int main() {
    int i;
    for (i=0; i<10; i++) printf(".");
    return 0;
}

输出:

..........

在Python中:

>>> for i in range(10): print('.')
.
.
.
.
.
.
.
.
.
.
>>> print('.', '.', '.', '.', '.', '.', '.', '.', '.', '.')
. . . . . . . . . .

在Python中,print将添加\n或空格,如何避免这种情况?现在,这只是一个例子,不要告诉我我可以先构建一个字符串然后再打印它.我想知道如何将字符串附加"到stdout.

In Python print will add a \n or space, how can I avoid that? Now, it's just an example, don't tell me I can first build a string then print it. I'd like to know how to "append" strings to stdout.

推荐答案

在Python 3中,您可以使用 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中,您可以使用 __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.

但是,请注意,在从Python 2中从__future__导入的print函数的版本中,flush关键字不可用;它仅适用于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.

这篇关于如何在没有换行符或空格的情况下进行打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-24 15:18