Printing without newline (print 'a',) prints a space, how to remove?
There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplication as @Ant mentions. This is only going to work if each of your print
statements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20
works).
>>> print 'a' * 20
Printing Without Newline (Print 'A',) Prints a Space, How to RemovePrinting Without Newline (Print 'A',) Prints a Space, How to Removeaaaa
If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print
. Note that string concatenation using +=
is now linear in the size of the string you're concatenating so this will be fast.
>>> for i in xrange(20):
... s += 'a'
...
>>> print s
Printing Without Newline (Print 'A',) Prints a Space, How to RemovePrinting Without Newline (Print 'A',) Prints a Space, How to Removeaaaa
Or you can do it more directly using sys.stdout.write(), which print
is a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 a
s.
>>> import sys
>>> for i in xrange(20):
... sys.stdout.write('a')
...
Printing Without Newline (Print 'A',) Prints a Space, How to RemovePrinting Without Newline (Print 'A',) Prints a Space, How to Removeaaaa>>>
Python 3 changes the print
statement into a print() function, which allows you to set an end
parameter. You can use it in >=2.6 by importing from __future__
. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.
>>> from __future__ import print_function
>>> for i in xrange(20):
... print('a', end='')
...
Printing Without Newline (Print 'A',) Prints a Space, How to RemovePrinting Without Newline (Print 'A',) Prints a Space, How to Removeaaaa>>>
How to print without a newline or space
In Python 3, you can use the sep=
and end=
parameters of the print
function:
To not add a newline to the end of the string:
print('.', end='')
To not add a space between all the function arguments you want to print:
print('a', 'b', 'c', sep='')
You can pass any string to either parameter, and you can use both parameters at the same time.
If you are having trouble with buffering, you can flush the output by adding flush=True
keyword argument:
print('.', end='', flush=True)
Python 2.6 and 2.7
From Python 2.6 you can either import the print
function from Python 3 using the __future__
module:
from __future__ import print_function
which allows you to use the Python 3 solution above.
However, note that the flush
keyword is not available in the version of the print
function imported from __future__
in Python 2; it only works in Python 3, more specifically 3.3 and later. In earlier versions you'll still need to flush manually with a call to sys.stdout.flush()
. You'll also have to rewrite all other print statements in the file where you do this import.
Or you can use sys.stdout.write()
import sys
sys.stdout.write('.')
You may also need to call
sys.stdout.flush()
to ensure stdout
is flushed immediately.
How do I keep Python print from adding newlines or spaces?
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.
how print in python loop with space and without new line
Try this:
num = [4 , 2]
for item in num:
for i in range(item):
print(item, end=" ")
print()
Edit:
I think it's overcomplicated for a problem like this, but you can try (it shouldn't print extra space at the end):
num = [4 , 2]
for item in num:
for i in range(item):
if item - 1 == i:
print(item)
else:
print(item, end=" ")
It prints an item with a new line when it's the last number in the second loop otherwise it prints the number with a space.
How can I suppress the newline after a print statement?
The question asks: "How can it be done in Python 3?"
Use this construct with Python 3.x:
for item in [1,2,3,4]:
print(item, " ", end="")
This will generate:
1 2 3 4
See this Python doc for more information:
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
--
Aside:
in addition, the print()
function also offers the sep
parameter that lets one specify how individual items to be printed should be separated. E.g.,
In [21]: print('this','is', 'a', 'test') # default single space between items
this is a test
In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest
In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test
Removing extra new lines with print() in python
This is because each line includes newline character(s), and print prints a newline character after everything else, for a total of up-to 2 newlines (the last line might have only 1).
You could strip the newline characters from the line.
f = open("foo.txt",'r')
for line in f:
print(line.rstrip('\r\n'))
Related Topics
Seeking from End of File Throwing Unsupported Exception
How to Add a Question Mark [] Button on the Top of a Tkinter Window
How to Upload a File to Directory in S3 Bucket Using Boto
Python Pack() and Grid() Methods Together
How to Leave/Exit/Deactivate a Python Virtualenv
How to Implement Band-Pass Butterworth Filter with Scipy.Signal.Butter
Finding Index of Nearest Point in Numpy Arrays of X and Y Coordinates
How to Run a Python Script in a Web Page
How to Get a List of Column Names in SQLite
How to Convert Defaultdict to Dict
How to Control the Mouse in MAC Using Python
Matplotlib - Add Colorbar to a Sequence of Line Plots
How to Output to the Same Line Overwriting the Previous Line
In Python, How to Test If I'm in Google App Engine Sdk
Accessing the List While Being Sorted
Why Doesn't Django's Model.Save() Call Full_Clean()
How to Treat Python Argparse.Namespace() as a Dictionary
Why Does the 'Is' Operator Behave Differently in a Script VS the Repl