Python: Print without Newline

In this article, we'll examine how to print a string without a newline character using Python.

In Python, the built-in print function is used to print content to the standard output, which is usually the console. By default, the print function adds a newline character at the end of the printed content, so the next output by the program occurs on the next line.

Try running this code to see an example:

print('Banana')
print('pudding.')

Output:

Banana
pudding.

As expected, the output of each print statement is shown on its own line.

However, in some cases we may want to output multiple strings on the same line using separate print statements. There are a few ways to prevent Python from adding the newline character when using the print function, depending on whether we are using Python 2.x or Python 3.x.

For example, this kind of functionality is useful for when you're developing a REPL or any command line application that takes input from the user, and you don't want the prompt and input text to be on different lines.

For Python 2.x, we can simply add a comma after the print function call, which will terminate the printed string with a space instead of a newline character:

print('Banana'),
print('pudding.')

Output:

Banana pudding.

In Python 3.x, we can use the end keyword argument in the print method to specify the termination character for the printed string:

print('Banana', end=' ')
print('pudding.')

Output:

Banana pudding.

So in this case, a space is used as the "termination" character, which results in the printed strings to be on the same line and only separated by a single space.

About the Author

This article was written by Jacob Stopak, a software consultant and developer with a passion for helping others improve their lives through code. Jacob is the creator of Code Card - a convenient tool for developers to look up, copy, and paste common code snippets.

Last Updated: July 9th, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Jacob StopakAuthor

Jacob Stopak is a software developer and creator of InitialCommit.io - a site dedicated to teaching people how popular programs are coded. Its main project helps people learn Git at the code level.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms