Understanding Python's print() Function: Default Newline Behavior and How to Print on the Same Line
This article explains why Python's print() adds a newline by default, demonstrates how to modify the end parameter or use rstrip() to print multiple outputs on a single line, and provides clear code examples for customizing print behavior when processing files.
Python's print() function outputs text and, by default, appends a newline character ( \n ) because the built‑in end parameter is set to "\n" . This causes each call to start on a new line.
The default behavior can be observed with a simple example:
<code># using print with default settings
print("This will be printed")
print("in separate lines")
</code>Both statements are printed on separate lines because end="\n" adds a line break after each call.
To print on the same line, you can change the end argument. Setting it to an empty string or a space prevents the automatic newline:
<code># Customizing the value of 'end'
print("This is string 1 same line", end=' ')
print("This is string 2 different line")
</code>The output shows the two strings separated only by the chosen space instead of a newline.
You can also use a custom separator, such as a semicolon:
<code># Customizing the value of 'end' with a custom separator
print("This is string 1 same line", end=';')
print("This is string 2 different line")
</code>Another common use case is printing items from a list on one line:
<code># iterating lists
list_fruits = ['red', 'blue', 'green', 'orange']
for i in list_fruits:
print(i, end=' ')
</code>All fruit names appear on a single line separated by spaces.
When reading a file, each line ends with \n , which can produce extra blank lines when printed. Using rstrip() (or rstrip('\n') ) removes the trailing newline, and combining it with end='' prints the file contents continuously.
<code>print("1. Removing extra blank line")
fhand = open('rainbow.txt')
for line in fhand:
line = line.rstrip()
print(line)
print("\n")
print("2. Printing all in the same line")
fhand = open('rainbow.txt')
for line in fhand:
line = line.rstrip('\n')
print(line, end=' ')
</code>These techniques eliminate unwanted blank lines and allow full control over how output is formatted on the console.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.