Joining values in print: sep and end
A date is three numbers: day 15, month 3, year 2026. How do you print them as 15.3.2026? Here are the tools you have so far:
day = 15
month = 3
year = 2026
print(str(day) + "." + str(month) + "." + str(year))
print(day, ".", month, ".", year)
print(f"{day}.{month}.{year}")
15.3.2026
15 . 3 . 2026
15.3.2026Joining with + works, but only strings can be joined, so every number needs its own str. The commas version needs no str, but print puts a space between the values, and here the spaces are wrong. The f-string gets it right.
The + way has a trap: leave out one str, and the program stops.
day = 15
print("Day " + day)
Traceback (most recent call last):
File "main.py", line 2, in <module>
print("Day " + day)
~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to strThe separator: sep
When you give print several values with commas, it puts a space between them. That space isn't fixed: you can choose another separator with the sep argument, written after the values as sep= and a string. The first line here solves the date problem:
print(15, 3, 2026, sep=".")
print("a", "b", "c", sep=", ")
print("no", "spaces", "at", "all", sep="")
print("one", "line", "each", sep="\n")
15.3.2026
a, b, c
nospacesatall
one
line
eachsep="" joins the values with nothing between them, and "\n" is the line break character, so sep="\n" puts each value on a line of its own.
sep is a keyword argument: it's given with its name, sep=, instead of by its position. That's how print can tell it from the values to print.
The end of the line: end
Every print ends its line with a line break, so the next print starts on a new line. The keyword argument end sets what comes at the end instead:
print("Loading", end="")
print("...", end="")
print("done")
for i in range(1, 6):
print(i, end=" ")
print()
print("Next line")
Loading...done
1 2 3 4 5
Next lineWith end="" the next print goes on in the same line. In the loop, end=" " keeps all the numbers in one line, with a space after each, and the empty print() at the end finishes that line. Without it, Next line would be printed right after the 5.
You can give both sep and end in one call: print(1, 2, sep="+", end="=3\n") prints 1+2=3.