Python Tutorial Python Advanced Python References Python Libraries

Python print() Function



The Python print() function is used to print object(s) to the standard output device or to the text stream file.

Please note that, sep, end and file, if present, must be given as keyword arguments.

Syntax

print(object, sep, end, file)

Parameters

object Required. Specify object/objects to be printed.
sep Optional. Specify separator. Objects will be separated by separator. Default: ' '
end Optional. Specify end to be printed at last. Default: None
file Optional. Specify file. It must be an object with a write(string) method. If not present or None, sys.stdout will be used.

Example: using print() statement

In the example below, print() function is used to print two string object separated by default separator ' '.

str1 = "Hello"
str2 = "World!"
print(str1, str2)

The output of the above code will be:

Hello World!

Example: using print() with sep and end parameters

In this example, print() function is used to print two string object separated by ' @ ' and end with '\n'.

str1 = "Hello"
str2 = "World!"
str3 = "Python"
print(str1, str2, sep=' @ ', end='\n')
print(str1, str3, sep=' @ ', end='\n')

The output of the above code will be:

Hello @ World!
Hello @ Python

Example: using print() with file parameter

In this example, print() function tries to open test.txt file if exists, else test.txt file is created and opened in write mode. After that, the function writes the given string object in the file. Finally, the file is closed. The file is again opened in read mode to read its content.

MyFile = open("test.txt", "w")
print("Hello World!", file=MyFile)
MyFile.close()

MyFile = open("test.txt", "r")
print(MyFile.read())

The output of the above code will be:

Hello World!

❮ Python Built-in Functions