This is a Chinese to English translation, please provide the English translation for this text. Do not provide any explanations or text apart from the translation.
English: ## Python2 and Python3 print without Line Break
Category Programming Techniques
This article mainly introduces how to achieve the effect of no line break in the print function under Python2 and Python3.
Python 3.x
In Python 3.x, we can add the parameter end=""
to the print() function to achieve the effect of no line break.
In Python 3, the default value of the print function's parameter is "\n"
, that is, end="\n"
, which means a new line. Assigning an empty value, that is, end=""
, will prevent the line from breaking. For example:
Python 3.x Example
print('This is a string,', end="")
print('this string here will not start a new line')
Executing the above code, the output result is:
This is a string, this string here will not start a new line
end=""
can be set to some special symbols or strings:
Example
print('12345', end=" ") # Set space
print('6789')
print('admin', end="@") # Set symbol
print('tutorialpro.org')
print('Google ', end="tutorialpro ") # Set string
print('Taobao')
Executing the above code, the output result is:
12345 6789
[email protected]
Google tutorialpro Taobao
Python 2.x
In Python 2.x, you can use a comma ,
to achieve the effect of no line break:
Python 2.x Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print "This is a string,", # Add a comma at the end
print "This string here will not start a new line"
# print with parentheses
print ("This is a string,"), # Add a comma at the end
print ("This string here will not start a new line")
Executing the above code, the output result is:
This is a string, This string here will not start a new line
This is a string, This string here will not start a new line
If there are variables, we can directly add variables after the comma ,
:
Python 2.x Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
x = 2
print "The number is:", x
Executing the above code, the output result is:
The number is: 2
Note: This output method will output a space at the end of the comma ,
, similar to using Python 3's end=" "
.
Python 2.x and Python 3.x Compatibility Mode
If you want to use the Python 3.x print function in the Python 2.x version, you can import the __future__
package, which disables the Python 2.x print statement and uses the Python 3.x print function.
The following code can be executed correctly in both Python 2.x and Python 3.x:
Python 2.x Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import print_function
print('12345', end=" ") # Set space
print('6789')
print('admin', end="@") # Set symbol
print('tutorialpro.org')
print('Google ', end="tutorialpro ") # Set string
print('Taobao')
Note: Many compatibility design features between Python 3.x and Python 2.x can be imported through the __future__
package.
**Click to Share Notes
-
-
-