Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in Python by (1.6k points)

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

2 Answers

0 votes
by (10.9k points)

Python 3, the print statement is actually a function and you can do the following:

print('.', end='')

You may also flush the output in case, you are having some problem with buffering:

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

 For Python 2.6 and higher, You can use the print(‘.’, end=’’) function by importing from __future__ import print_function

 For Python 2, you can use the print(‘.’, end=’’) function provided you have used from __future__ import print_function but the flush keyword is not available in Python 2 so you have to flush it manually using the sys.stdout.flush() .

 The simplest way is:

import sys

sys.stdout.write('.')

 Then to flush stdout use:

sys.stdout.flush()

Hope this helps!

0 votes
by (106k points)
edited by

To print without new line in Python you can use the following code:-

strings = [ "one", "two", "three" ] 

for i in xrange(3): 

    print("Item %d: %s" % (i, strings[i]))

To know more about this you can have a look at the following video:-

Related questions

0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Jul 22, 2019 in DevOps and Agile by humble gumble (19.4k points)

Browse Categories

...