Last updated: Apr 9, 2024
Reading time·3 min
To print a horizontal line:
print()
function to print the horizontal line.print('─' * 25)
.# ✅ Print a horizontal line print('─' * 25) # 👉️ ──────────── print('⸻' * 25) # 👉️ ⸻⸻⸻⸻⸻ print('⸺' * 25) # 👉️ ⸺⸺⸺⸺⸺⸺⸺⸺ print('*' * 25) # 👉️ ************
The examples use the multiplication operator to print a horizontal line.
When the multiplication operator is used with a string and an integer, the string is repeated the specified number of times.
print('─' * 25) # 👉️ ────────────
You can use this approach to print a horizontal line that consists of any character.
If you need to print the items in an iterable horizontally, set the end argument of the print() function to a string containing a space.
my_list = ['bobby', 'hadz', 'com'] for item in my_list: print(item, end=' ') # 👉️ bobby hadz com
The end
argument is printed at the end of the message.
By default, end
is set to a newline character (\n
).
print('a', 'b', 'c') # 👉️ 'a b c\n' print('a', 'b', 'c', end='') # 👉️ 'a b c'
Alternatively, you can use the iterable unpacking operator.
print(*my_list) # 👉️ bobby hadz com
The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.
You can use this approach to print the items of an iterable with any separator, it doesn't have to be a space.
my_list = ['bobby', 'hadz', 'com'] print(*my_list, sep='─') # 👉️ bobby─hadz─com
The
sep
argument is the separator between the arguments we pass to print()
.
By default, the argument is set to a space.
Use the multiplication operator to print multiple blank lines.
When the multiplication operator is used with a string and an integer, it repeats the string the specified number of times.
print('before') print('\n' * 3) print('after') # before # after
We used the multiplication operator to print multiple blank lines.
print('a' * 2) # 👉️ 'aa' print('a' * 3) # 👉️ 'aaa'
The \n
character represents a new line in Python.
However, note that the print()
function adds a newline (\n
) character at the
end of each message.
# 👇️ Adds a newline character automatically print('a', 'b', 'c') # 👉️ 'a b c\n' # 👇️ Set `end` to empty string to remove newline character print('a', 'b', 'c', end='') # 👉️ 'a b c'
The end
argument is printed at the end of the message.
By default, end
is set to a newline character (\n
).
If you need to remove the newline \n
character the print()
function adds by
default, set the end
keyword argument to an empty string.
print('before', end='') print('\n' * 3) print('after', end='') # before # after
When the end
keyword argument is set to an empty string, no newline character
is added at the end of the message.
I've also written a detailed guide on how to repeat a string N times.
You can learn more about the related topics by checking out the following tutorials: