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

PythonPrintingFormattingPython 2.x

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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.

Solution 3 - Python

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)

Solution 4 - Python

Or use a +, i.e.:

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

Just make sure all are concatenate-able objects.

Solution 5 - Python

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.

Solution 6 - Python

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.

Solution 7 - Python

This may look stupid, but seems to be the simplest:

    print 'h',
    print '\bm'

Solution 8 - Python

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, ...).

Solution 9 - Python

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:

    import sys
    Print = sys.stdout.write
    Print("Hello")
    Print("World")

will yield:

HelloWorld

That is all.

Solution 10 - Python

In python 2.6:

>>> print 'h','m','h'
h m h
>>> from __future__ import print_function
>>> print('h',end='')
h>>> print('h',end='');print('m',end='');print('h',end='')
hmh>>>
>>> print('h','m','h',sep='');
hmh
>>>

So using print_function from _future_ you can set explicitly the sep and end parameteres of print function.

Solution 11 - Python

You can use print like the printf function in C.

e.g.

print "%s%s" % (x, y)

Solution 12 - Python

print("{0}{1}{2}".format(a, b, c))

Solution 13 - Python

sys.stdout.write is (in Python 2) the only robust solution. Python 2 printing is insane. Consider this code:

print "a",
print "b",

This will print a b, leading you to suspect that it is printing a trailing space. But this is not correct. Try this instead:

print "a",
sys.stdout.write("0")
print "b",

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 your print:

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, or sys.stdout.write, or something else? If you make two consecutive calls to print, then Python will insist on putting in a space in between the two.

Solution 14 - Python

print('''first line \
second line''')

it will produce

> first line second line

Solution 15 - Python

import sys
a=raw_input()
for i in range(0,len(a)):
       sys.stdout.write(a[i])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBartView Question on Stackoverflow
Solution 1 - PythonFederico A. RamponiView Answer on Stackoverflow
Solution 2 - PythonGreg HewgillView Answer on Stackoverflow
Solution 3 - PythonDanView Answer on Stackoverflow
Solution 4 - PythonpabloView Answer on Stackoverflow
Solution 5 - PythontzotView Answer on Stackoverflow
Solution 6 - PythonBrianView Answer on Stackoverflow
Solution 7 - PythonAbdView Answer on Stackoverflow
Solution 8 - PythonJohn MachinView Answer on Stackoverflow
Solution 9 - PythonjokerView Answer on Stackoverflow
Solution 10 - PythonBenjaminView Answer on Stackoverflow
Solution 11 - Pythontechdude101View Answer on Stackoverflow
Solution 12 - PythonMichael MurphyView Answer on Stackoverflow
Solution 13 - PythonAaron McDaidView Answer on Stackoverflow
Solution 14 - Pythonahmed khattabView Answer on Stackoverflow
Solution 15 - PythonMrinalView Answer on Stackoverflow