How do I keep Python print from adding newlines or spaces?


Question

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.

1
228
2/23/2015 9:10:58 AM

Accepted Answer

You can use:

sys.stdout.write('h')
sys.stdout.write('m')
195
10/31/2008 10:35:49 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon