How do I keep Python print from adding newlines or spaces? [duplicate]
Asked Answered
J

15

246

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.

Jamnis answered 31/10, 2008 at 22:33 Comment(1)
My current experiments suggest there is no trailing space. Instead, it is a leading space if and only if the preceding output operation was a print. To see yourself, interleave some calls to print '.', and sys.stdout.write(','). This is crazy. Why should it 'remember' what came before, and change behaviour accordingly?Volatilize
A
203
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.

Annelieseannelise answered 31/10, 2008 at 22:35 Comment(4)
This worked great for me. Just don't forget to do a sys.stdout.flush() when you're ready to display it on screen, otherwise it will hold it in a buffer and you won't see it. I use this to give visual feedback that a script is still running when it's going through a long while or for loop.Hendeca
If typing is an issue, don't forget you can do: log = sys.stdout.writeThine
To use this, you have to import sys by using import sysPositivism
As a variation on this idiom: prynt = lambda x : sys.stdout.write (str(x))Stalactite
U
306

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

Uke answered 31/10, 2008 at 22:44 Comment(3)
You can from __future__ import print_function in Python 2.6Demetriusdemeyer
from future import print_function will break any other print statements using the old syntax in the same module, so whilst it's more elegant than sys.stdout.write, it can be more work to make the change.Lapointe
Also handy, if you need to overwrite the last line, use end='\r'Ferrara
A
203
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.

Annelieseannelise answered 31/10, 2008 at 22:35 Comment(4)
This worked great for me. Just don't forget to do a sys.stdout.flush() when you're ready to display it on screen, otherwise it will hold it in a buffer and you won't see it. I use this to give visual feedback that a script is still running when it's going through a long while or for loop.Hendeca
If typing is an issue, don't forget you can do: log = sys.stdout.writeThine
To use this, you have to import sys by using import sysPositivism
As a variation on this idiom: prynt = lambda x : sys.stdout.write (str(x))Stalactite
C
44

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)
Clausewitz answered 31/10, 2008 at 22:53 Comment(1)
as a variation on this idiom: print ''.join(map(str,[1, '+', 2, '=', 3]))Stalactite
P
27

Or use a +, i.e.:

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

Just make sure all are concatenate-able objects.

Parsonage answered 4/1, 2009 at 11:27 Comment(2)
or, you can convert them: print str(me)+str(no)+str(likee)+str(spacees)+str(pls)Allyl
This still adds a newline.Timepiece
C
19
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.

Canescent answered 1/11, 2008 at 0:21 Comment(0)
S
17

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.

Stillman answered 1/11, 2008 at 0:43 Comment(1)
according to documentation This attribute is not used to control the print statement, but to allow the implementation of print to keep track of its internal state.Rudie
V
13

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

    print 'h',
    print '\bm'
Valdemar answered 19/12, 2013 at 9:32 Comment(1)
This still adds a newline.Timepiece
T
8

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

Tachygraphy answered 24/6, 2009 at 4:26 Comment(1)
I loved this :D. A good thing about it is that it implicitly kills the problem of "something %s" % x where x is a tuple...Zig
S
7

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.

Selvage answered 13/10, 2014 at 15:46 Comment(0)
R
4

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.

Reconcile answered 23/4, 2014 at 14:27 Comment(0)
R
1

You can use print like the printf function in C.

e.g.

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

Rubber answered 26/1, 2014 at 22:6 Comment(1)
This still adds a newline afterwards. The OP wanted to call print multiple times over a loop and not have any spaces or newlines in between.Argentite
D
1
print("{0}{1}{2}".format(a, b, c))
Dupion answered 10/7, 2014 at 21:13 Comment(2)
This still adds a newline afterwards. The OP wanted to call print multiple times over a loop and not have any spaces or newlines in between.Argentite
… but it is a good idea to have a read of the format documentation: string — § Format String Syntax and Built-in Types — § String Methods — str.formatStalactite
V
0

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.

Volatilize answered 4/12, 2014 at 13:41 Comment(0)
A
0
print('''first line \
second line''')

it will produce

first line second line

Abel answered 18/2, 2017 at 19:21 Comment(0)
S
-1
import sys
a=raw_input()
for i in range(0,len(a)):
       sys.stdout.write(a[i])
Shag answered 18/4, 2015 at 7:21 Comment(1)
The accepted answer by Greg Hewgill already mentioned sys.stdout.write().Argentite

© 2022 - 2024 — McMap. All rights reserved.