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(objects,聽sep=' ',聽end='\n',聽file=sys.stdout,聽flush=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聽None,聽sys.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 my project. Thank you! 馃檹