Python print() Method
print() method prints the given object to the console or to the text stream file.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
- objects: One or more objects to be printed, seperated by a space ' ' by default.
- Sep: (Optional) If multiple objects passed, they are separated by the specified separator. Default is ' '.
- end: (Optional) The last value to print. Default is '\n'.
- file: (Optional) Must be an object with
write(string)method. Default is sys.stdout.
- flush: (Optional) The stream is forcibly flushed if buffered. Default is False.
The following example demonstrates the
print("Learning Python") name = 'John' print("My name is",name)
Learning Python My name is John
We can pass various parameters to alter the output.
name = 'John' print("My name is",name,sep='---',end = "\n\n\n\n") print("I am 18 years old")
My name is---John I am 18 years old
The following prints the object to the file.
printtofile = open('debug.txt', 'w') print('printing to file', file = printtofile) printtofile.close()
>>> name="Ram" >>> age=21 >>> print(name, age, sep=",") Ram,21
The output of the
print() function always ends by the NEWLINE character.
print() function has another optional parameter
end, whose default value is
\n, which can be substituted by any other character such as a single space (' ') to display the output of the subsequent
print() statement in the same line, as shown below.
>>> name="Bill" >>> age=21 >>> print(name, end=" "); print(age) Bill 21
Note that the output is displayed in a single line even if there are two
It is possible to format the output using C style format specifier symbols such as
%d, %f, %s, etc. Learn about it in the Python String.