How do I keep Python print from adding newlines or spaces? [duplicate]
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.
In Python 3, use
print('h', end='')
to suppress the endline terminator, and
print('a', 'b', 'c', sep='')
to suppress the whitespace separator between items. See the documentation for print
import sys
sys.stdout.write('h')
sys.stdout.flush()
sys.stdout.write('m')
sys.stdout.flush()
You need to call sys.stdout.flush()
because otherwise it will hold the text in a buffer and you won't see it.
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)