📅  最后修改于: 2023-12-03 14:46:03.058000             🧑  作者: Mango
In Python, the built-in print()
function is commonly used to display output on the console. By default, it appends a new line character (\n
) after each call. However, there are situations where you might want to print without a new line.
end
parameter of the print()
functionThe print()
function in Python has an optional end
parameter that determines what character(s) are used to separate consecutive calls. By default, end='\n'
, which adds a new line after each print statement. To print without new lines, you can change the end
parameter to an empty string:
print("Hello", end='')
print("World", end='')
print("!", end='')
Output:
HelloWorld!
As seen in the above example, the print statements are concatenated without new lines because the end
parameter is set to an empty string.
sep
parameter of the print()
functionApart from the end
parameter, the print()
function also has a sep
parameter. It specifies the separator between multiple objects printed by one print()
statement. By default, sep=' '
adds a space character between objects. To print without new lines, you can set sep
to an empty string:
print("Hello", "World", "!", sep='')
Output:
HelloWorld!
By setting sep
to an empty string, the objects are concatenated without any separator, resulting in a single string without new lines.
sys.stdout.write()
functionAnother way to print without new lines is to use the sys.stdout.write()
function. This function writes a string to the standard output without appending a new line:
import sys
sys.stdout.write("Hello")
sys.stdout.write("World")
sys.stdout.write("!")
Output:
HelloWorld!
Note that the sys.stdout.write()
function does not automatically add a new line, so you need to manually include spaces or new lines if needed.
In this guide, we explored various methods to print without new lines in Python. You can achieve this by modifying the end
parameter of the print()
function to an empty string, setting the sep
parameter to an empty string, or using the sys.stdout.write()
function. Choose the method that best suits your requirements and coding style.