Python print() without newline
In Python 3.x , you can use the optional end="" argument to the print() function to prevent a newline character from being printed.
for item in [1,2,3,4]:
print(item, " ", end="")
output
1 2 3 4
without end="" argument:

In Python 2.x , you can use a trailing comma:
print 'Hello', ' World!'
output
Hello World!
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
from __future__ import print_function
to get access to the Python 3 print function.
__future__ is a pseudo-module which programmers can use to enable new language features which are not compatible with the current interpreter. Also, it needs to be the first line of code in your script.
In addition, the print() function in Python 3.x also offers the sep parameter that lets one specify how individual items to be printed should be separated.
sys.stdout.write
A built-in file object that is analogous to the interpreter's standard output stream in Python . Unlike print, sys.stdout.write() doesn't switch to a new line after one text is displayed. To achieve this one can employ a new line escape character(\n) .
import sys
for item in ['a','b','c','d']:
sys.stdout.write(item)
output
abcd
In fact, wherever a print function is called within the code, it is first written to sys.stdout and then finally on to the screen.
Difference between sys.stdout.write and print
The print is just a thin wrapper that formats the inputs and calls the write function of a given object. It first converts the object to a string (if it is not already a string) and also put a space before the object if it is not the start of a line and a newline character at the end. While using stdout , you need to convert the object to a string yourself (by calling "str", for example) and there is no newline character . The return value for sys.stdout.write() returns the no. of bytes written which also gets printed on the interactive interpret prompt for any expressions enter.
Related Topics
- How to use Date and Time in Python
- Python Exception Handling
- How to Generate a Random Number in Python
- How to pause execution of program in Python
- How do I parse XML in Python?
- How to read and write a CSV files with Python
- Threads and Threading in Python
- Python Multithreaded Programming
- Python range() function
- How to Convert a Python String to int
- Python filter() Function
- Difference between range() and xrange() in Python
- How to remove spaces from a string in Python
- How to get the current time in Python
- Slicing in Python
- Create a nested directory without exception | Python
- How to measure time taken between lines of code in python?
- How to concatenate two lists in Python
- How to Find the Mode in a List Using Python
- Difference Between Static and Class Methods in Python?