How to print without newline or space?

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 .


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)

It should be as simple as described at this link by Guido Van Rossum:

Re: How does one print without ac/r ?

http://legacy.python.org/search/hypermail/python-1992/0115.html

Is it possible to print something but not automatically have a carriage return appended to it ?

Yes, append a comma after the last argument to print. For instance, this loop prints the numbers 0..9 on a line separated by spaces. Note the parameterless "print" that adds the final newline:

>>> for i in range(10):
...     print i,
... else:
...     print
...
0 1 2 3 4 5 6 7 8 9
>>> 

Note: The title of this question used to be something like "How to printf in python?"

Since people may come here looking for it based on the title, Python also supports printf-style substitution:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

And, you can handily multiply string values:

>>> print "." * 10
..........
链接地址: http://www.djcxy.com/p/2168.html

上一篇: 使用按位或0来放置一个数字

下一篇: 如何在没有换行符或空格的情况下打印?