How to print without newline or space?

2018-12-30 23:31发布

The question is in the title.

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

#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.

26条回答
栀子花@的思念
2楼-- · 2018-12-31 00:03

i recently had the same problem..

i solved it by doing:

import sys, os

# reopen stdout with "newline=None".
# in this mode,
# input:  accepts any newline character, outputs as '\n'
# output: '\n' converts to os.linesep

sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)

for i in range(1,10):
        print(i)

this works on both unix and windows ... have not tested it on macosx ...

hth

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 00:04

The new (as of Python 3.0) print function has an optional end parameter that lets you modify the ending character. There's also sep for separator.

查看更多
看淡一切
4楼-- · 2018-12-31 00:04

You can try:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')
查看更多
素衣白纱
5楼-- · 2018-12-31 00:06

Here's a general way of printing without inserting a newline.

Python 3

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

In Python 3 it is very simple to implement

查看更多
后来的你喜欢了谁
6楼-- · 2018-12-31 00:10

You will notice that all the above answers are correct. But I wanted to make a shortcut to always writing the " end='' " parameter in the end.

You could define a function like

def Print(*args,sep='',end='',file=None,flush=False):
    print(*args,sep=sep,end=end,file=file,flush=flush)

It would accept all the number of parameters. Even it will accept all the other parameters like file, flush ,etc and with the same name.

查看更多
孤独总比滥情好
7楼-- · 2018-12-31 00:11

Using functools.partial to create a new function called printf

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

Easy way to wrap a function with default parameters.

查看更多
登录 后发表回答