views:

7847

answers:

10

In python, if I say

print 'h'

I get the letter h and a newline. If I say

print 'h',

I get the letter h and no newline. If I say

print 'h',
print 'm',

I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?

The print statements are different iterations of the same loop so I can't just use the + operator.

+26  A: 

You can use:

sys.stdout.write('h')
sys.stdout.write('m')
Greg Hewgill
+24  A: 

Just a comment. In Python 3, you will use

print('h', end='')

to suppress the endline terminator, and

print('a', 'b', 'c', sep='')

to suppress the whitespace separator between items.

Federico Ramponi
You can `from __future__ import print_function` in Python 2.6
J.F. Sebastian
+4  A: 

print "%s%s%s%s" % ('a','s','d','f')

Dustin Getz
+13  A: 

Greg is right-- you can use sys.stdout.write

Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then

lst = ['h', 'm']
print  "".join(lst)
Dan
+1  A: 
print 'h' + 'e',

stupid python :-)

( seriously, it's a great language... but this is just stupid! )

why stupid ? that seems logical to me :)
hayalci
+7  A: 
Python 2.5.2 (r252:60911, Sep 27 2008, 07:03:14)
[GCC 4.3.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print "hello",; print "there"
hello there
>>> print "hello",; sys.stdout.softspace=False; print "there"
hellothere

But really, you should use sys.stdout.write directly.

ΤΖΩΤΖΙΟΥ
+4  A: 

For completeness, one other way is to clear the softspace value after performing the write.

import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"

prints helloworld !

Using stdout.write() is probably more convenient for most cases though.

Brian
+2  A: 

Using the print statement without a formatting operation first is really only for very basic convenience. If you want to control the format of the output at all, then do as Dustin says: use a format string.

Ned Batchelder
+2  A: 

lol

or use a '+', i.e.;

print 'me'+'no'+'likee'+'spacees'+'pls'

menolikeespaceespls

just make sure all are concatenate-able objects

or, you can convert them:print str(me)+str(no)+str(likee)+str(spacees)+str(pls)
fengshaun
+3  A: 

Regain control of your console! Simply:

from __past__ import printf

where __past__.py contains:

import sys
def printf(fmt, *varargs):
    sys.stdout.write(fmt % varargs)

then:

>>> printf("Hello, world!\n")
Hello, world!
>>> printf("%d %d %d\n", 0, 1, 42)
0 1 42
>>> printf('a'); printf('b'); printf('c'); printf('\n')
abc
>>>

Bonus extra: If you don't like print >> f, ..., you can extending this caper to fprintf(f, ...).

John Machin