Tip: Use print() with additional arguments

Patrick Loeber

We all know the print function in Python

print("Hello World")

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

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 *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses