This question already has an answer here:
- How to print without newline or space? 26 answers
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.
sys.stdout.write
is (in Python 2) the only robust solution. Python 2 printing is insane. Consider this code:This will print
a b
, leading you to suspect that it is printing a trailing space. But this is not correct. Try this instead:This will print
a0b
. How do you explain that? Where have the spaces gone?I still can't quite make out what's really going on here. Could somebody look over my best guess:
My attempt at deducing the rules when you have a trailing
,
on yourprint
:First, let's assume that
print ,
(in Python 2) doesn't print any whitespace (spaces nor newlines).Python 2 does, however, pay attention to how you are printing - are you using
print
, orsys.stdout.write
, or something else? If you make two consecutive calls toprint
, then Python will insist on putting in a space in between the two.it will produce
For completeness, one other way is to clear the softspace value after performing the write.
prints
helloworld !
Using stdout.write() is probably more convenient for most cases though.
I am not adding a new answer. I am just putting the best marked answer in a better format. I can see that the best answer by rating is using
sys.stdout.write(someString)
. You can try this out:will yield:
That is all.
You can use print like the printf function in C.
e.g.
print "%s%s" % (x, y)