Home Python How to print without newline in Python

How to print without newline in Python

You might want to print a value on the screen when programming, but keep it on the same line as your displayed last value. In addition, you might, for example, want a user’s first and last name to show on the same line. If you find yourself here, you need to master various techniques that will help you achieve this.

Print is one of the first commands for any learner to encounter in virtually every programming language. The role is to display the output on the terminal in the case of Python.

In Python, print works differently from most of the other languages. Because it displays output separately in a new line by default, whereas others show results from several prints on the same line. It happens by default in Python. For instance,

print("print the first line !")
print("print the second line !")
show output in a seperate line
show output in a separate line

How can you make print() behave differently if you don’t want your message to be displayed with newlines or spaces? Or, with Python, how can you print without a newline?

This is accomplished by changing the default values of the print() function’s sep and end parameters.

All you need to do is put more arguments to the end of the respective statement to print without a newline. The end is the name of this argument. We’ll learn more about this and other approaches in this article as follows.

using the “end” argument in In the print statement

Upon utilizing the print() function in Python 3, the output is printed on multiple lines each time. You can circumnavigate this by assigning an empty string to the end parameter. As a result, the following output will not be displayed on a new line. We can change the example above in the following way.

# using_end.py
print("print the first line!", end=' ')
print("print the second line!")
using end to display two statements in one line
using end to display two statements in one line

You must now use a space at the end of your first print function if you want to introduce a space in your output. For instance, in the example we have used, we will make the following changes.

print("print the first line! ", end = ' ' )
print("print the second line!")

Using Python 3.X’s “sys module” Library to Print Without a Newline

Another option for printing without a newline in Python is to utilize the built-in module sys. The following is a practical use of the sys module to output Python strings without newlines.

To interact with the sys module, first, use the import keyword to import the sys module. Then, to print your strings, use the sys module’s stdout.write() method.

#Import the inbuilt sys library
import sys
#output from the first line
sys.stdout.write("print the first line.")
# output of the second line
sys.stdout.write("Print the second line.")
sys module Library to Print Without a Newline
sys module Library to Print Without a Newline

Explanation of the Code

Python’s sys module contains several functions and variables for working with the runtime environment. In addition, this module includes information about the Python interpreter’s functions, constants, and methods.

A file object called sys.stdout is used to display the result of a print statement. There is no newline at the end of a string printed by the sys.stdout.write() method.

In the code, both strings are printed on the same line, with no spaces between them. Note that the output of both of the preceding examples will be on a single line, with no space between the strings.

In Python, the print function has two little-used arguments

The argument sep indicates the separator written between the objects.
What appears after each line is defined by the argument end.

Illustration:

# declararion of example strings
var1 = 'Toyota'
var2 = 'BMW'

# Usual behavior of print()
print(var1, var2)

# Use the separator and end arguments
print(var1, var2, sep=' is different from ', end='!')
using sep and end
using sep and end

Code explanation:

You can format the output using the print function’s arguments.

The argument indicates the separator between the objects sep. The default value for sep is empty. This is because we used the words “is different from” in the puzzle.

What appears after each line is defined by the argument end. The end is set to a line break by default. We set it to ‘!’ in the puzzle. Because there is no line break, the print will print everything in one continuous line.

We receive the output ‘Toyota is different from BMW!’ when we execute print() with the specified arguments and objects var1 and var2.

Printing a “List” with a “for” Loop without introducing a new line

# Python program to print list without a newline character

# declare a list of your favorite cars
listcars = ['Toyota', 'BMW', 'Suzuki', 'Nissan']

# use a for the list to print the entire list
for car in listcars:
    print(car, end='')
print a list with a for loop without introducing a new line
print a list with a for loop without introducing a new line

Code walk-through

The components of a list are saved in a variable named listcars in the program mentioned above. Then, a for loop iterates over the elements and prints them out one by one. An end parameter is passed to the print statement, as you can see. It prevents the strings from being printed on separate lines.

The elements in the list are all printed on the same line, with no spaces between them.

Printing List Items with a Space Between Them

What is the best way to print a list?

# Python program to print list without a newline character

# declare a list of your favorite cars
listcars = ['Toyota', 'BMW', 'Suzuki', 'Nissan']

# use a for the list to print the entire list
for car in listcars:
    print(car, end='  ')
Printing List Items with a Space Between Them
Printing List Items with a Space Between Them

Code Explanation:

Using the print command, a for loop iterated over list elements to print them out on the same line. It is accomplished by giving an empty string as the value of the end argument. The single quotes have a space between them, as can be seen in the code. Thus, it adds a space between the list elements when printed on a single line.

Alternative to print a list

Do you wish to send a list of commands to the shell? Follow these easy steps:

The print() method in Python accepts a list as an input.
To “unpack” the list into the print function, use the asterisk operator * in front of the list.
Use the sep option to specify how two list members should be visually separated.

Example:

# Create the Python List
lst = [1, 2, 3, 4, 5,6,7,8,9,10]

# Use an underscore as a separator
print(*lst, sep='_')

# Use an arrow as separator
print(*lst, sep='-->')
Use the sep to seperate a list
Use the sep to separate a list

It is the most Pythonic and efficient way to print a Python list.

Separation using a comma


We can also use a comma to separate multiple items in a print() function in python. We will illustrate as follows.

var1 = 'Toyota'
var2 = 'BMW'
var3 = 'Suzuki'
var4 = 'Nissan'

print(var1, var2, var3,var4)
Separation using a comma
Separation using a comma

Because we’re displaying two strings, Python will combine them using the default value of sep, a blank space. Python also appends a newline character to the end of the line, causing the interpreter prompt to jump to the end.

Unpacking


There is, however, a more complex solution that is both more concise and Pythonic. It makes use of Python’s unpacking functionality. For example:

print(*range(1,10))
Unpacking
Unpacking

Before the range(1,10), the asterisk prefix * unpacks all values in the range iterable into the print function. It resembles the function execution print(1, 2, 3, 4,5,6,7,8,9,10) with comma-separated arguments in this way. In the print() function, you can pass any number of arguments.

Python will print these arguments with a space between them by default. However, you can use the sep option to customize this separator string, as you learned previously.

Conclusion

Many first-time users may find printing with Python inconvenient because most other programming languages need the position of a new line to be indicated in the program. However, it saves time because it recognizes a new line in the output with each print function or expression.

In this post, we looked at the many methods for printing data without using a newline character or carriage return. When printing the items in the outputs of algorithms like a binary tree or printing the contents of a list next to each other, this method can be pretty helpful.

All you have to do is end your print function with the argument ‘end’ in Python 3 or use sys.stdout or choose one of the other approaches we have looked at whenever you need an output written on the same line.

This easy addition will assist you in overcoming your new line issues!

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More