Print() in Python

A guide to printing and formatting your scripts output.

Keno Leon
Keno Leon
Feb 8 · 8 min read
Why read this ?While a basic print statement can serve you well, you will be printing a lot while debugging and getting results from your scripts, as such, it is a good investment, additionally it will help you read others code and look at some more advanced use cases.print('Win Win')

Basics

We all start here:

print(‘Hello World’)# OUTPUT:Hello World

If you want to separate the output into different lines, just use \n

print('Hello \nWorld')# OUTPUT:Hello
World

Numbers require you to cast them as strings :

print ('this is line: ' + str(1))
print ('this is line: ' + str(2))
# OUTPUT:This is line: 1
This is line: 2

And of course you can wrap everything in a function and print the output:

def gDay():    
return ('Good Day Sir !')
print(gDay())# OUTPUT:Good Day SirOr Inside the function, can get messy but works:def gDay():
print ('Good Day Madam')
gDay()# OUTPUT:Good Day Madam

Printing is also a very handy way to inspect variables and objects:

Using a list, but could be a Tuple,Dictionary,or any iterable.list = [i+1 for i in range(10)]print(list)
print(list[3])
# OUTPUT:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4
If you want to print text plus one of these, try a comma ,print('LIST:' ,list)#OUTPUT:LIST: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Objects/classes are slightly more complex because you need to differentiate between the class itself and the instance/ instance method :

class simpleObject():
def simpleObject_method(self):
return ('Hello again')
print(simpleObject)
# Prints the class:
<class '__main__.simpleObject'>a = simpleObject() # << making a class instanceprint(a)
# Prints the instance:
<__main__.simpleObject object at 0x100bf7588>print(a.simpleObject_method())
# prints the instance method:
Hello again

These I think are some common basics that will cover most of your day to day, but printing can get better and become even more useful with some extra effort and know how…

Intermediate Printology :

Probably the first roadblock one encounters when printing is concatenating multiple variables along with some text, this can easily be done ( in fact we already did a couple of examples ago ) by separating things with a + sign:

var_1 = 'This is number: '
numbers = [1,2,3]
print( var_1 + str(numbers[0]) + ' The only one !')>> This is number: 1 The only one !
# ⚠️ >> is interchangeable with OUTPUT:

print( var_1 + str(numbers[1]) )
>> This is number: 2print( numbers[0] + numbers[1] + numbers[2])>> 6Note that the last example adds the numbers up, you need to cast/convert them to strings to print them.

This could be considered a simple way of formatting your output, but it is by now means the only one, the following section deals with Python’s formatting function :

#Same example using a formatter, don't worry if it doesn’t make much sense yet, just note that the output is the same as above:numbers = [1,2,3]print("This is number: {0} the only one !".format(numbers[0]))>> This is number: 1 the only one !print("This is number: {0}".format(numbers[1]))>> This is number: 2

Understanding Python’s formatter is half the battle, so let’s start with the basic template:

text = 'Hello there'
print("{}".format(text))
>> Hello there

The utility of the format() function comes (primarily) when adding more than one value:

text_1 = 'Hello there'
text_2 = 'General Kenobi'
print("{}...{}".format(text_1, text_2))
>> Hello there...General Kenobi

Variables get added in the order the {} are added, so our revised template could be:

You can add as many variables as you need ( here 3 for simplicity ):

text_1 = 'Hello Henchman'
text_2 = 'Oddjob'
henchmanRank = [1,2,3,4,5]
print("{} {} You are my number {}".format(text_1, text_2, henchmanRank[1]))>> Hello Henchman Oddjob You are my number 2

If keeping track of your replacement variables is proving difficult or you need to replace the order you can use index numbers as so:

firstName =  'James'
lastName = 'Bond'
print ('The name is {1}...{0} {1}'.format(firstName,lastName))>> The name is Bond...James BondYou could also name your replacement variables:lastName = 'Bond'
print ('The name is {0}...{firstName} {0}'.format(lastName, firstName = 'Jim'))
>> The name is Bond...Jim Bond

And how about formatting ? If you notice we haven’t had to convert to strings our numbers, and that is another benefit of using format() , yet this is only the beginning, you can format to your hearts content by using a special syntax, here’s a few common examples:

# Add a coma :print('{:,}'.format(1000))   
>> 1,000
# Add a coma and display 2 decimal points:print('${:,.2f}'.format(1000))
>> $1,000.00
# Express percentages with 2 decimal points:sureness = 80/99
print ('I am sure about this: {:.2%}'.format(sureness))
# >> I am sure about this: 80.81%
# Show only 2 decimal places:floaty = 10.2222222
print('floaty value is {:.2f} '.format(floaty))
>> floaty value is 10.22
# Round and show 2 decimals:
floaty = 10.2299999
print('floaty value is {0:.2f} '.format(round(floaty,2)))
>> floaty value is 10.23

This subject is somehow deep, so I encourage you to consult the documentation for a look at what else you can format (dates, tables, hex values and on and on ):

⚠️ Note: There is an older syntax for formatting strings % along with a newer one we will cover next, I focused so far on the intermediate one.

f-strings:

A third way of formatting and fast becoming the norm are f-strings, which if you have been following along will be easy to comprehend since they are basically a shorter form of format() , in a nutshell:

let’s rewrite the previous format()examples:

text = 'Hello there'
print(f'{text}')
>> Hello there

More values no problem:

text_1 = 'Hello there'
text_2 = 'General Kenobi'
print(f"{text_1}...{text_2}")>> Hello there...General Kenobi

Revised template:

text_1 = 'Hello Henchman'
text_2 = 'Oddjob'
henchmanRank = [1,2,3,4,5]
print(f"{text_1} {text_2} You are my number {henchmanRank[1]}")>> Hello Henchman Oddjob You are my number 2

Using them with functions:

def to_uppercase(text):
return text.upper()
firstName = 'Bond'
print(f"{to_uppercase(firstName)}!...James {firstName}")
>> BOND!...James Bond

And of course you can format everything like with format() :

# Add a coma :print(f"{1000:,}")

>> 1,000
# Add a coma and display 2 decimal points:print(f"${1000:,.2f}")>> $1,000.00# Express percentages with 2 decimal points:
sureness = 80/99

print(f"I am sure about this: {sureness:.2%}")
>> I am sure about this: 80.81%# Show only 2 decimal places:floaty = 10.2222222print(f"floaty value is {floaty:.2f}")>> floaty value is 10.22# Round and show 2 decimals:floaty = 10.2299999
print(f"floaty value is {round(floaty,2):.2f}")
>>floaty value is 10.23

Like with format() , using and mastering f-Strings is a question of practice, they are relatively new, so use them if your environment allows it.

A second opinion Doc ? Couple of tutorials on fstrings you might also like :https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-pythonhttp://zetcode.com/python/fstring/

Becoming a master printologist ( Dr. printer, I presume )

If you were to expand your knowledge on formatting and couple it with other python idioms and functions, you could do something like this:

results = [10.22111, 30.33, 40.69999]print('\n'.join(‘ Index: {0} Original {1:>10}, Rounded: {1:>.2f}'.format(*k) for k in enumerate(results)))>>Index: 0 Original   10.22111, Rounded: 10.22
Index: 1 Original 30.33, Rounded: 30.33
Index: 2 Original 40.69999, Rounded: 40.70

Explanation: We simply wanted to see what a list of results would look like in their original form, rounded and their list index in an uncluttered readout, we are using 2 new (to us) functions, enumerate and join, but the rest should look familiar, new in the formatting part are the > symbols, which right align and give breadth to the central column.
With f-strings:print ('\n'.join(f" Index: {i} Original: {k:>10}, Rounded: {k:>.2f}" for i, k in enumerate(results)))
Perhaps more readable:
for i,result in enumerate(results):
print (f" Index: {i} Original: {result:>10}, Rounded: {result:>.2f}")

So in one sense you are halfway there, the rest is adding new knowledge to the basics presented here and elsewhere.

Another route is to use a library to supplement your printing needs, there are a few out there for tabular data, here’s one example:

Using Tabulate:Install: pip install tabulateUsage:from tabulate import tabulatetable = [["LexL","SuperMan",0.00],["Joker","HarleyQ",0.00],["Bane","Batman",0.00]]headers = ["Villain", "Nemesis", "Success Rate %"]print(tabulate(table, headers, tablefmt="fancy_grid", floatfmt=".1f"))OUTPUT:╒═══════════╤═══════════╤══════════════════╕
│ Villain │ Nemesis │ Success Rate % │
╞═══════════╪═══════════╪══════════════════╡
│ LexL │ SuperMan │ 0.0 │
├───────────┼───────────┼──────────────────┤
│ Joker │ HarleyQ │ 0.0 │
├───────────┼───────────┼──────────────────┤
│ Bane │ Batman │ 0.0 │
╘═══════════╧═══════════╧══════════════════╛
One line of code to print a pretty table I think is a great deal, the caveat here is that you might need extra features and you need to learn to use the library.

I guess the final frontier of printing is moving away from the terminal and into the real world, for that you will need to export whatever you are printing into a document format like a pdf, here’s a barebones example that uses tabulate:

Setup: You need to install a binary/executable (wkhtmltopdf) and a package/library (Pdfkit).Install wkhtmltopdf
Install Pdfkit >> pip install pdfkit
Usage (With tabulate):import pdfkit
from tabulate import tabulate
table = [["LexL","SuperMan",0.00],["Joker","HarleyQ",0.00],["Bane","Batman",0.00]]
headers = ["Villain", "Nemesis", "Success Rate %"]
exportTable = tabulate(table, headers, tablefmt="html", floatfmt=".1f")pdfkit.from_string(exportTable, 'Villains.pdf')
Notes: There's very little difference from the previous example, we are generating a table with tabulate but saving it as a variable in html format, we later feed this to pdfkit and generate our pdf.

Result:

If you want to follow this route, the next step might be to add html formatting and templating, (jinja for instance):

Also check other reporting libraries:

Conclusions:

Most likely you will be using print() a lot while coding in python, and as such I hope you now have some extra insight into the different ways and cases you can use it, from printing for quick inspection, formatting complex printouts and even some basic reports.

tl;dr: Use print() for inspections and small things, format() and f-strings for complex readouts and libraries/complex formatters for advanced and exportable printouts and reports.

Happy printing and thanks for reading !

Keno Leon

Written by

Keno Leon

AI, Software Developer, Designer : www.k3no.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade