How to Print Horizontal Lines and Control Newlines in Python
This guide explores various techniques for printing horizontal lines and managing newlines in Python. We will cover printing basic horizontal lines with character repetition, printing list items horizontally, inserting multiple blank lines, and removing trailing newlines.
Printing a Horizontal Line
To print a horizontal line using a single character, use the multiplication operator with a string and an integer:
print('─' * 25)
print('⸻' * 25)
print('⸺' * 25)
print('*' * 25)
output
─────────────────────────
⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻
⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺⸺
*************************
- This approach is very simple to use, and you can use any character and any number.
Printing List Items Horizontally
To print items from a list horizontally (on the same line), use the print()
function's end
argument with a space as separator or the iterable unpacking operator:
my_list = ['tutorial', 'reference', 'com']
# Using the end argument with a space
for item in my_list:
print(item, end=' ') # Output: tutorial reference com
# Using the iterable unpacking operator
print(*my_list) # Output: tutorial reference com
print(*my_list, sep='-') # Output: tutorial-reference-com
- Using the
end
parameter causes each element of the list to be printed, and the specified string (in this case a space) is added after every element. - The iterable unpacking operator (
*
) unpacks the list items in the call to print which causes them to be printed on the same line by default, using a space as a separator, or using a separator specified with thesep
parameter.
Printing Multiple Blank Lines
To print multiple blank lines, use the multiplication operator with the newline character '\n'
:
print('before')
print('\n' * 3)
print('after')
output
before
after
The newline character causes a new line to be inserted, and the multiplication operator prints multiple newline characters.
Removing Trailing Newline Characters
The print()
function automatically adds a newline character at the end of its output. To remove this, set the end
argument to an empty string (''
):
print('a', 'b', 'c')
print('a', 'b', 'c', end='')
print('before', end='')
print('\n' * 3)
print('after', end='')
output
a b c
a b cbefore
after
- When the
end
argument is set to empty string, no new line will be added automatically.