Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print without a newline or space

Tags:

python

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 range(10): 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.

like image 898
Andrea Ambu Avatar asked Jan 29 '09 20:01

Andrea Ambu


People also ask

How do I print without going to the next line?

You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

How do you print without newline in Python 2?

In python2. x you can add a comma (,) at the end of the print statement that will remove newline from print Python.


2 Answers

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.

like image 123
codelogic Avatar answered Oct 06 '22 10:10

codelogic


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 >>> 
like image 26
KDP Avatar answered Oct 06 '22 10:10

KDP