Categories
python

How to print without a newline or space

2286

Example in C:

for (int i = 0; i < 4; i++)
    printf(".");

Output:

....

In Python:

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

In Python, print will add a \n or space. How can I avoid that? I’d like to know how to “append” strings to stdout.

4

3106

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.

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

which allows you to use the Python 3 solution above.

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.

Or you can use sys.stdout.write()

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

You may also need to call

sys.stdout.flush()

to ensure stdout is flushed immediately.

5

  • 11

    Thanks! In Python 3.6.3, that flush=True is crucial, or else it doesn’t work as intended.

    – gunit

    Jan 11, 2018 at 5:28

  • 8

    Can someone explain why would I need to flush and what does it do actually?

    – Rishav

    Feb 4, 2019 at 21:16

  • 10

    It’s a few months late, but to answer @Rishav flush empties the buffer and displays the output right now. Without flush you might have your exact text printed eventually, but only when the system gets around to processing the graphics instead of the IO. Flush makes the text visible immediately by “flushing” the cache.

    Jun 20, 2019 at 11:55

  • 3

    If you’re having trouble with buffering you can unbuffer all python output with python -u my.py. This is often a good idea if you want to watch progress in real-time.

    Sep 15, 2020 at 23:30

  • I use format strings and do not want a new line between the string and the ?:line = f"{line[6:]}?" Is there also an “end”?

    – Timo

    Nov 30, 2020 at 18:59


300

For Python 2 and earlier, it should be as simple as described in Re: How does one print without a CR? by Guido van Rossum (paraphrased):

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

11

  • 109

    This is specifically listed in the question as undesirable behavior because of the spaces

    – Zags

    Jun 12, 2015 at 20:30

  • 96

    On the contrary, the answer should be deleted for two reasons: it has undesirable side effects which you can’t disable (included extra spaces), and It isn’t forward compatible with python 3 (the parenthesis force a conversion to a tuple). I expect these sorts of shoddy constructs from PHP, not Python. So it’s best to not ever use this.

    Jul 26, 2015 at 16:48


  • 11

    // , This is the simplest way to get it done in Python 2, though, and there is a LOT of one-off code out there for really old OSes. Probably not the best solution, or even recommended. However, one of the great advantages of StackOverflow is that it lets us know what weirdo tricks are out there. KDP, would you include a quick warning at the top about what @Eric Leschinski said? It does make sense, after all.

    Aug 31, 2015 at 19:05

  • 25

    @nathanbasanese Simple or not, it has a side effect that the asker explicitly does not want. Downvoted.

    – Shadur

    Dec 7, 2015 at 9:40

  • 5

    How can I get rid of that space after each N i.e. I want 0123456..

    – AKS

    Mar 7, 2017 at 1:30


178

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

7

  • 11

    Indeed, it is missing the point. 🙂 Since there was already a great answer to the question I was just elaborating on some related techniques that might prove useful.

    – Beau

    Jan 30, 2009 at 21:41

  • 8

    Based on the title of the question, I believe this answer is more appropriate analog to how one commonly uses printf in C/C++

    – Dan

    Aug 1, 2009 at 1:47

  • 17

    This answers the title of the question, but not the body. That said, it provided me with what I was looking for. 🙂

    – ayman

    Oct 7, 2009 at 1:13

  • 2

    it’s not the answer to the question

    – Vanuan

    Jul 5, 2012 at 15:03

  • 4

    @Vanuan, I explained in the bottom of my answer that the title of the question changed at some point. 🙂

    – Beau

    Jul 6, 2012 at 18:45