Table of Content
- How to Use the print() Function in Python
- What are the Additional Arguments of Python print() Function
- Wrap Off
Most python developers are familiar with the print()
function in Python.
But many do not know that it can also take optional keyword-only arguments.
In this post, you will learn about the python various additional arguments of the Python print()
function and how to use them.
How to Use the print() Function in Python
Firstly, here's the format for the python print()
function.
The first parameter, which is the objects
is the most commonly used.
It accepts the correct value of any data type and outputs it.
You can also print other data types such as lists, dictionaries, sets, tuples, objects, classes, etc.
And you can have multiple types get printed at once using a comma-separator or concatenation of all types as strings.
print(“Hello World”, 111, False, 1.900)
print(f"Hello World, {111}, {False}, {1.900}")
What are the Additional Arguments of Python print() Function
Now, we have seen the objects. Let's have a look at the other arguments of the print()
function in Python.
The additional arguments of the python print()
function are:
1. The sep argument in the Python print() function
The sep
argument in the Python print() function is used to define the separator between all objects.
By default, it is a space, but we can change it:
2. The end argument in the Python print() function
The end
in the Python print() function defines the character in the end.
By default, the character at the end of every printed object is a new-line character.
For example, we can omit a new line with this:
3. The file argument in the Python print() function
The file
in the Python print() function defines where the output should be displayed.
The file argument must be an object with a write(string)
method; if it is not present or None
, sys.stdout
will be used.
This creates a file test.txt containing the text “Test file content”.
Since printed arguments are converted to text strings, print()
cannot be used with binary mode file objects.
For these, use file.write(...)
instead.
4. The flush argument in the Python print() function
The flush
in the Python print() function defines whether the output should be flushed or not.
The default is False
.
Whether the output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
Wrap Off
There you have it!
If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.
Please share this post and for more insightful posts on business, technology, engineering, history, and marketing, subscribe to our newsletter.