Skip to content

Tip - The print function can take additional arguments

Learn what additional arguments you can use for the print function.


We all know the print function in Python

print("Hello World")

But do you know it also takes optional keyword-only arguments:

  • print(objectssep=' 'end='\n'file=sys.stdoutflush=False*)

sep argument for print

sep defines the separator between all objects. By default it is a space, but we can change it:

print("How", "are", "you", sep="-")
# How-are-you

end argument for print

end defines the character in the end, which by default is a new-line character. For example, we can omit a new line with this:

print("Hello", end="")
print("World")
# HelloWorld

file argument for print

The file argument must be an object with a write(string) method; if it is not present or Nonesys.stdout will be used.

f = open("test.txt", "a")

print("This goes into a file", file=f)

f.close()

This creates a file test.txt containing the text.

Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Whether the output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.


FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*


Python Problem-Solving Bootcamp

🚀 Solve 42 programming puzzles over the course of 21 days: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏