tags:

views:

12289

answers:

5

The question is in the title.

I'd like to do in Python what I 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 make a string then print it. I'd like to know how to "append" strings to the stdout (I don't know if it's worded correctly).


I know about the comma, did you read my Python example?!?

+11  A: 
import sys
sys.stdout.write('.')

or

print('.'), # this will still print a space, but not a newline
codelogic
Won't the second example also print ten spaces?
Triptych
@Triptych: I tried it - it does.
xtofl
Yup, thanks I'll specify it.
codelogic
+1  A: 

Try adding a comma:

print "Hi",
print "There"

Check here for more details: http://blog.code-head.com/print-without-a-new-line-or-space-in-python

Mike Robinson
+2  A: 

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

SilentGhost
+34  A: 

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
..........
Beau
String value multiplication is amazing. Great answer.
Nick Stinemates
This is missing the point.
Andrea Ambu
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
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
This answers the title of the question, but not the body. That said, it provided me with what I was looking for. :)
ayman
This is the second search result for `python printf` on Google.
Joey Adams
A: 

Print without a space or newline:

print "text" + "\r",
Therms
it doesn't work :O
Andrea Ambu