Python: Print without a newline

In Python, when you use the print() function, it will automatically add a newline at the end of the string that you’re printing out. But what if you want to print without a newline?

To print without a newline in Python, you need to add an extra argument to your print function that tells the program that you don’t want the next string to start on a new line.

Method 1: Using the end argument

The simplest way to print without a new line is to use the built-in end argument for the print function. By default, the print function ends with a newline character, which is why we see each string on a separate line.

However, we can override this behavior by specifying the end argument. For example, let’s say we want to print the string “Hello, world!” without adding a newline afterwards. We would do this as follows:

print("Hello, ", end="") print("World!!!")
Code language: Python (python)

Output: “Hello, World!!!”

As you can see, all we need to do is pass in an empty string for the end argument. Now when we run our code, we’ll see that “Hello, world!” is printed without a new line afterwards:

Method 2: Using sys.stdout.write

Another way to print without a new line is by using sys.stdout.write. This is similar to the previous method, but it gives us a bit more control over what gets printed and when. Let’s take a look at an example:

import sys sys.stdout.write("Hello, ") sys.stdout.write("world!")
Code language: Python (python)

Output: “Hello, world!”

Here, we start by importing sys, which gives us access to various system-specific parameters and functions.

We then use sys.stdout.write to print our string without adding a newline afterwards. When we run our code, we’ll see that “Hello, world!” is printed without a newline afterwards.

Using the .join() method

The .join() method takes an iterable object (like a list) as its first argument and a string as its second argument.

It returns a new string that is the concatenation of all the strings in the iterable object, separated by the string that was passed in as the second argument.

So, to print out our list of strings without any newlines, we would do this:

strings = ['first', 'second', 'third'] print(', '.join(strings))
Code language: PHP (php)

This would print out: first, second, third

In this blog post, we showed you three ways to print without adding a newline in Python: by using the built-in end argument, using the .join() method, and using sys.stdout.write.

While these methods are effective, we recommend using the end argument if possible—it’s simpler and easier to remember!

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts