How can we print output without a line break in Python?
There are two ways to print without a new line in Python.
- When using the end parameter of the print function, the default value is “\n”, which means it ends with a new line character. By setting the end parameter value to an empty string “”, you can achieve printing without a new line. For example:
print("Hello", end="")
print("World") # 输出结果为:HelloWorld
- Using the sys module’s stdout object: The sys module is a Python system-related functionality module, and the sys.stdout object represents the standard output stream. By modifying the properties of sys.stdout, you can achieve printing without line breaks. For example:
import sys
sys.stdout.write("Hello")
sys.stdout.write("World\n")
Both of the above methods can achieve the effect of printing output without line breaks, the specific choice of which method depends on actual needs and personal preferences.