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

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.

This question is related to python printing formatting python-2.x

The answer is


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.


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

it will produce

first line second line


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)

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

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


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.


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.


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

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

    print 'h',
    print '\bm'

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.


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


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.


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.


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)

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.


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)

Or use a +, i.e.:

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

Just make sure all are concatenate-able objects.


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.


Or use a +, i.e.:

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

Just make sure all are concatenate-able objects.


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


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.


You can use print like the printf function in C.

e.g.

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


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.


Or use a +, i.e.:

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

Just make sure all are concatenate-able objects.


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


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.


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.


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)

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

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


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.


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

    print 'h',
    print '\bm'

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

it will produce

first line second line


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.


You can use print like the printf function in C.

e.g.

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


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

Or use a +, i.e.:

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

Just make sure all are concatenate-able objects.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to printing

How do I print colored output with Python 3? Print a div content using Jquery Python 3 print without parenthesis How to find integer array size in java Differences Between vbLf, vbCrLf & vbCr Constants Printing variables in Python 3.4 Show DataFrame as table in iPython Notebook Removing display of row names from data frame Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window Print a div using javascript in angularJS single page application

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to python-2.x

Combine several images horizontally with Python How to print variables without spaces between values How to return dictionary keys as a list in Python? How to add an element to the beginning of an OrderedDict? How to read a CSV file from a URL with Python? Malformed String ValueError ast.literal_eval() with String representation of Tuple Relative imports for the billionth time How do you use subprocess.check_output() in Python? write() versus writelines() and concatenated strings How to select a directory and store the location using tkinter in Python