This article is participating in Python Theme Month. See the link for details

How do I print without newlines in Python?

People often switch from C/C++ to Python and want to know how to print two or more variables or statements without entering a new line of Python. By default, the Python print() function ends with a newline character. Python has a predefined format that if you use print(a_variable) it automatically goes to the next line.

Here are some examples:

print("juejin")
print("jiuqi")
Copy the code

Can lead to this

juejin
jiuqi
Copy the code

But sometimes it might happen that we don’t want to go to the next line, we want to print on the same line. So what can we do? Such as:

Input : print("juejin") print("jiuqi")
Output : juejin jiuqi

Input : a = [1.2.3.4]
Output : 1 2 3 4 
Copy the code

The solution discussed here depends entirely on the version of Python you are using.

Print without newlines in Python 2.x

# Python 2 code for printing
Print on the same line
# juejin and jiuqi

print("juejin"),
print("jiuqi")

# array
a = [1.2.3.4]

Print an element on the same line
for i in range(4) :print(a[i]),
Copy the code

Output:

juejin jiuqi
1 2 3 4
Copy the code

Prints without newlines in Python 3.x

# Python 3 code for printing
Print on the same line
# juejin and jiuqi

print("juejin", end ="")
print("jiuqi")

# array
a = [1.2.3.4]

Print an element on the same line
for i in range(4) :print(a[i], end ="")

Copy the code

Output:

juejin jiuqi
1 2 3 4
Copy the code

The Python end argument in print()

By default, Python’s print() function ends with a newline character. Programmers with a C/C++ background may wonder how to print without newlines.

Python’s print() function takes an argument named “end”. By default, the value of this parameter is ‘\n’, which is a newline character. You can use this parameter to end a print statement with any character/string.

# This Python program must be run using Python 3, as it does not apply to 2.7
# End the output with 
      
print("Welcome to" , end = ' ')
print("juejin", end = ' ')
Copy the code

Output:

Welcome to juejin
Copy the code

Let’s use another program to demonstrate how closing arguments work.

# This Python program must be run using Python 3, as it does not apply to 2.7
# End output with "@"
print("Python" , end = The '@') 
print("juejin")
Copy the code

Output:

Python@juejin
Copy the code

This is the end of the article, thank you for reading 😊

If you find anything incorrect, or if you would like to share more information about the above topics, please comment and let us know.