How to Prevent Line Breaks with the print Function
print(<string>, end='')
print(<string>, end="")
Explanation
The print function outputs the given string concatenated with the value of the end argument. The default value of the end argument is the newline character ‘\n’, so specifying an empty string prevents a line break.Note: If you specify None, it is considered as if the argument was omitted, and a line break will be output.
Sample Code
The following sample code displays the string ‘Hello, World!’ with and without line breaks.print('With line break')
print('Hello, World!')
print('Hello, World!')
print('Without line break', end='')
print('Hello, World!', end='')
print('Hello, World!', end='')
Application: Outputting Empty Lines
If you specify two line breaks for the end argument, an empty line will be output.print('Output empty line', end='\n\n')
print('Hello, World!', end='\n\n')
print('Hello, World!', end='\n\n')
References
Test Environment
- Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32
- Microsoft Windows 10 Enterprise Version 22H2 OS Build 19045.3570 Experience: Windows Feature Experience Pack 1000.19052.1000.0