This article mainly describes how to achieve the no-newline effect with print in Python2 and Python3.

Python 3.x

In Python 3.x, we canprint()add in the functionend=""a parameter, thereby achieving the no-newline effect.

In Python3, the parameter of the print functionenddefault value is"\n", i.e.end="\n", which means newline. Setendan empty value, i.e.end="", and it will not wrap. For example:

Python3.x Example

print('This is a string,', end="")
print('The string here will not start a new line')

Executing the above code, the output is:

This is a string; the string here will not start on a new line.

end=""You can set some special symbols or strings:

Example

print('12345', end=" ")  # Set a space
print('6789')

print('admin', end="@")  # Set a symbol
print('example.com')

print('Google ', end="Example ")  # Set a string
print('Taobao')

Executing the above code, the output is:

12345 6789
[email protected]
Google Example Taobao

Python 2.x

In Python 2.x, you can use a comma,to achieve the no-newline effect:

Python2.x Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

print "This is a string,",         # Add a comma at the end
print "The string here will not start a new line"

# print with parentheses
print ("This is a string,"),        # Add a comma at the end
print ("The string here will not start a new line")

Executing the above code, the output is:

This is a string; the string here will not start on a new line.

If there is a variable, we can, after the comma,,directly add the variable:

Python2.x Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

x= 2
print "The number is:", x

Executing the above code, the output is:

字为: 2

Note:This output method, at the,end, will output a space, similar to using Python 3'send=" "。

Python2.x and Python3.x compatibility mode

If the Python2.x version wants to use Python3.x'sprintfunction, you can import the__future__package, which disables Python2.x's print statement and adopts Python3.x'sprintfunction.

The following code runs correctly in both Python2.x and Python3.x:

Python2.x Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from __future__ import print_function

print('12345', end=" ")  # Set a space
print('6789')

print('admin', end="@")  # Set a symbol
print('example.com')

print('Google ', end="Example ")  # Set a string
print('Taobao')

Note:Many compatibility features designed for Python3.x and Python2.x can be imported through__future__this package.