Python print() Function

Prints the message on the screen


The print() function prints the specified message to the screen or the text file. The message can be a string, or any other object (such as number, list, tuple etc.)



Python print() function parameters
objectsOptionalZero or more objects to print.
sepOptionalA string to print between each object.
Default is a single space ‘ ‘
endOptionalA string to print at the end.
Default is a newline ‘\n’.
fileOptionalAn object with a write(string) method.
Default is sys.stdout (screen)
flushOptionalIf True, output buffer is forcibly flushed

sep, end, file and flush must be specified as keyword arguments.

For example, sep = '-' or end = ' '

Basic Example

# Print the message on the screen
print('Hello, World!')
# Prints Hello, World!

You can print as many values as you like, just separate them with a comma ,.

# Prints One two three four five

Separator Parameter

When you print multiple values, each value is separated by a space ' '. By specifying sep parameter, you can separate each value by something other than a space.

# Separate each value with '...'
print('One','two','three', sep='...')
# Prints One...two...three

End Parameter

The print() function includes a newline \n at the end by default. To print the values without a trailing newline, specify end parameter.

# Print without newline
print('First line.', end=' ')
print('Next line')
# Prints First line. Next line

If no values are specified, print() will just print end parameter.

File Parameter

The print() function prints the values to the screen by default. However, you can print them to the file by specifying the file parameter.

with open('myfile.txt', 'w') as f:
    print('Hello, World!', file=f)

You can print any object other than string such as number, list, tuple etc. The object is converted into a string before written to the screen.

# Print a list
print(['red', 'green', 'blue'])
# Prints ['red', 'green', 'blue']

# Print a tuple
print((1, 2, 3))
# Prints (1, 2, 3)