笑故挽风 2009-01-29 20:58 采纳率: 100%
浏览 536
已采纳

如何打印没有换行或空间?

The question is in the title.

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;
}

Output:

..........

In Python:

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

In Python print will add a \n or a 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.

转载于:https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space

  • 写回答

26条回答 默认 最新

  • lrony* 2009-01-29 21:01
    关注

    General way

    import sys
    sys.stdout.write('.')
    

    You may also need to call

    sys.stdout.flush()
    

    to ensure stdout is flushed immediately.

    Python 2.6+

    From Python 2.6 you can import the print function from Python 3:

    from __future__ import print_function
    

    This allows you to use the Python 3 solution below.

    Python 3

    In Python 3, the print statement has been changed into a function. In Python 3, you can instead do:

    print('.', end='')
    

    This also works in Python 2, provided that you've used from __future__ import print_function.

    If you are having trouble with buffering, you can flush the output by adding flush=True keyword argument:

    print('.', end='', flush=True)
    

    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().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(25条)

报告相同问题?

悬赏问题

  • ¥20 六子棋博弈基于Alpha-Beta剪枝搜索算法的优化
  • ¥15 mlx90393用stm32f1的单片机使用软件i2c通信一直报错
  • ¥50 使用MS Log Parser查询使用Bitvise SSH Server登录的IP
  • ¥20 校园二手交易小程序搭建
  • ¥15 请问在ubuntu用conda创建环境报错怎么能解决
  • ¥15 STM32CubeMX/proteus按键控制指示灯颜色切换
  • ¥20 python,计算区位熵和扩张指数
  • ¥15 Python环境配置
  • ¥15 解决页面无法编入索引:被“noindex”标签排除的问题?
  • ¥15 arduino测量电阻