Suppose you have a variable in a Python program. You may want to know the content that the variable points to, to be able to figure out whether your program is running as planned. Or, when you are writing a quick program that does not rely on a graphical interface for input/output, you will want to show some quick prompts to the user for navigating through the program.
That’s where the Python
print() method comes in. The
print() method allows you to print an object — which can be something as basic as a string too — to the standard output device, which usually is the command prompt.
This tutorial discusses how to use the Python
print() method to print any object to the standard output. Let’s walk through an example to help you get started with this method.
Python print() Method
print() method prints an object to the standard output. You can print any object, including lists and strings, using the print command.
The syntax for the
print() method is as follows:
print(object1, object2, object3, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
The above command takes a number of arguments:
- objects: Receives the objects that are to be printed. These can be instances of user-defined classes or primitive objects like integers or strings.
- sep: Defines a separator between multiple objects. It is optional and works only if more than one object has been passed in for printing. Its default value is ‘ ’ or a single space character.
- end: Defines a character that will be appended at the end of the printed output. It is optional, and its default value is ‘\n’ meaning a plain print(“Hey”) command will print Hey and move the cursor to a new line.
- file: Another optional parameter that can be used to direct the output to a file or a similar output stream. The default value is sys.stdout, which stands for the command line output.
- flush: A boolean parameter, which specifies if the output will be flushed or not. A flushed output means that all print commands will directly take effect. In the other case, the system will try to accumulate consecutive print commands to execute them at once and improve performance. Its default value is False. While this is not something that you may use very often, it does come handy when creating complex applications.
You might notice that we use a ‘sep=’ prefix for specifying our separating character, and an ‘end=’ prefix for specifying the trailing character. The reason behind this is that the
print() command can take in multiple arguments for printing. If we were to pass the two formatting characters (sep and end) without their prefixes, the command would treat them as objects to be printed, and would print them on the output device.
print() Python Example
The best example of the
print() statement in Python is the traditional “Hello World!” program:
81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.
The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.
print("Hello World!") # Hello World!
If you are looking to print multiple strings one after another, here’s how you can pass in multiple arguments:
print("This is one.", "This is two.") # This is one. This is two.
You can try changing the separator between the two objects like this:
print("This is one.", "This is two.", sep='|') # This is one. | This is two.
This can come handy when you are printing multiple objects together, like when displaying a receipt’s details, or when displaying multiple details of an object together.
Now, let’s take things up a level and try to print the contents of a variable:
first_name = "John" last_name = "Doe" print(first_name, last_name, sep=' ') # John Doe
Let’s try calling two
print() commands back to back:
print("Hello") print("World") # Hello # World
What if you wanted them on the same line? You can do that with the end parameter:
print("Hello", end=' ') print("World") # Hello World
Occasionally, you might encounter situations where you may need to print the contents of some variables to a file. This might be needed in a large application which can not be monitored/debugged in real-time. Such files are called logs, and there are advanced libraries to help do this. For a relatively smaller application, you can use the print statement to generate adequate logs. Here’s how you can do that:
user = "John" with open(logs.txt', 'w') as f: print("User is " + user, file=f)
However, this is not a very popular method of writing to files, as other optimized methods like
file.write() exist for the same purpose.
Making Objects Print-Friendly
Objects in Python are instances of classes. They can contain more than one member variables and methods. This means that printing an object which has two member variables is not as simple as printing a plain string. There needs to be some way with which the print command can figure out what to do when an object of unknown type is passed in to be printed.
This is where the __str__ method comes in. This is a special method that can be defined in any class and is called by the print method when an object is passed in for printing. This method returns a string, which can be easily printed via the print command. This is how a general class with an __str__ method looks like:
class Test: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __str__(self): return "In the str method: a is % s, b is % s, c is % s" % (self.a, self.b, self.c)
The __str__ method is often used to fit the data of all the member variables into a template string that can be printed out for debugging purposes.
print() method outputs the passed objects to the set output device, which is by default the command line prompt. It takes in options like end and sep to help you format your output for better readability.
This tutorial discussed, with reference to examples, the basics of Python
print() and how to write classes that can support accessible print outputs. Now you are ready to start using the
print() method like a Python pro!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.