Python Language The Print Function Print parameters


You can do more than just print text. print also has several parameters to help you.

Argument sep: place a string between arguments.

Do you need to print a list of words separated by a comma or some other string?

>>> print('apples','bannas', 'cherries', sep=', ')
apple, bannas, cherries
>>> print('apple','banna', 'cherries', sep=', ')
apple, banna, cherries

Argument end: use something other than a newline at the end

Without the end argument, all print() functions write a line and then go to the beginning of the next line. You can change it to do nothing (use an empty string of ''), or double spacing between paragraphs by using two newlines.

>>> print("<a", end=''); print(" class='jidn'" if 1 else "", end=''); print("/>")
<a class='jidn'/>
>>> print("paragraph1", end="\n\n"); print("paragraph2")


Argument file: send output to someplace other than sys.stdout.

Now you can send your text to either stdout, a file, or StringIO and not care which you are given. If it quacks like a file, it works like a file.

>>> def sendit(out, *values, sep=' ', end='\n'):
...     print(*values, sep=sep, end=end, file=out)
>>> sendit(sys.stdout, 'apples', 'bannas', 'cherries', sep='\t')
apples    bannas    cherries
>>> with open("delete-me.txt", "w+") as f:
...    sendit(f, 'apples', 'bannas', 'cherries', sep=' ', end='\n')
>>> with open("delete-me.txt", "rt") as f:
...     print(
apples bannas cherries


There is a fourth parameter flush which will forcibly flush the stream.