Shaping Your Output: sep, end and \n · Python
Ch 2 · Your First Python Program — card 3 of 3.
- How sep changes what goes between the values you print
- How end changes what goes at the end of a line
- How \n starts a new line inside a piece of text
By default, print() puts a space between each value and moves to a new line when it finishes. Most of the time that is exactly what you want, but you can change both. Adding sep="-" tells Python to put a dash between the values instead of a space, which is handy for dates or lists. Adding end="" stops print() from starting a new line, so the next print() carries on along the same line. Inside any piece of text, the two characters \n mean "start a new line here", so one print() can show several lines. Finally, a print() with nothing inside the brackets prints an empty line, which is a simple way to space out your output and make it easier to read.
# sep changes what goes BETWEEN the values
print("2026", "09", "23", sep="-")
print("red", "green", "blue", sep=", ")
# end changes what goes at the END (normally a new line)
print("Loading", end="")
print("...", end=" ")
print("done!")
# \n inside a string starts a new line
print("Line one\nLine two")
# An empty print() gives you a blank line
print()
print("The end")- sep sits between values and is a space unless you change it
- end comes after the last value and is a new line unless you change it
- \n is written as two characters but counts as one new line