Python print() and beyond

Subscribe to my newsletter and never miss my upcoming articles

Beyond the print() function in Python

Hey guys, today I am going to talk about some features of the print() function in python. You will probably have come across some of these functions while others could seem new.

Let's start by understanding the basics of the print function. In python, the built-in print function is used to print all kinds of stuff - text, numbers, objects, dictionaries etc. But how does this function handle that ?! You might think; it just can do it, it was made for that. But in reality, the print function in python can only handle strings.

Under the hood, anything you pass to the print() function gets converted to a string before being printed to your screen. That mean it will make use of the str() type casting and convert all other data types to strings before displaying them to your console/terminal. Now that you know how the print() work, let's dive into its features.

Furthermore, print doesn't know how to print text to the screen. I won't go detail into that for now. Later in this post, you will know what happens under it.

Basically, you can print whatever you want . The simplest example you have come across is print("Hello World!") It take a string enclosed in double quotes or single quotes and prints it. You can also print multiple stuff by simply separating them with comas as such :

name = "Mike"
age = 24
print("Hello", name, "Your age is", age)
# output : Hello Mike Your age is 24

You can as well print text that takes more than a line. In this case, you will be using the newline escape character \n Example :

print("Hello \nWorld")
# Output : 

You can also format text with it. Making use of f-strings

name = "Samson"
print(f"Hello {name}")
# Output : Hello Samson

The example above showcase the basics of the print function. It can take a variable number of values to print. Other than that, there are also some keyword arguments. Let's dive into them

1. Separator

print() allows you to decide what separates text we print with it. By default, all the values you pass to it are separated by empty strings. But we change that. It suffices to include sep= followed by whatever you want to separate your text. Let's make use of the previous example.

name = "Mike"
age = 24
print("Hello", name, "Your age is", age, sep="-")
# output : Hello-Mike-Your age is-24

You notice that all what we passed into it separately are separated by a -. You can modify that however you want. You just need to make sure the separator is a valid string.

2. Ending

You can specify by whatever you want your output to end with. By default, what you print end with a newline escape character \n. Let's change that and see what happens

# without modified end character
print("Hello James")
print("How are you doing")
# Output
# Hello James
# How are you doing

# with modified end character
print("Hello James", end="")
print("How are you doing", end="")
# Output
# Hello JamesHow are you doing

If we execute that, we notice the text is no more separated by a new line. Let's try that again! But this time, we want it to end by y and move to a new line.

print("Hello James", end="y\n")
print("How are you doing", end="\n")

We get the following output

Hello Jamesy
How are you doingy

Yay it worked !

3. Writing to a file

At the beginning of this post, I said python doesn't know how to print stuff to the screen by itself. It rather uses sys.stdout and writes your text to that file. Wait what ! Print will write text to a file object which I sent to your screen via sys.stdout. Therefore, you can modify this behaviour too in order to have this printed elsewhere. Let's give it a try. Write the following code:

with open("hello.txt", "w") as file_object:
        print("This message is for you", file=file_object)

Executing the above will end in a file name hello.text in the same directory with the text This message is for you in it. Therefore, we can direct where we want our text to be printed. In this case, we created a file name hello.txt and use the file keyword argument to direct the result to be written to that file rather than our terminal. You can use this to direct any result to wherever you want, even through a socket connection.

4. Flushing

This one requires an example. Let's have one!

import time

names = ["John", "Sylvia", "Smith"]

for name in names:
    print(name, end=" ")

What this code should do is; print a name after a second. Try and run it and see what happens. You notice it unexpectedly waits and print all at once. This is because since it's on a single line, it is all buffered (packed) before we get it. Read more about buffers here But we could go around that by simply adding the flush= keyword argument to the print function. By default it it set to False. Setting it to true will ensure every print statement is executed and freed from buffer before the next one. The following code will make it :

import time

names = ["John", "Sylvia", "Smith"]

for name in names:
    print(name, end=", ", flush=True)

If you run it. It will print a name, sleep for a second and print another, all on the same line. Yay we did it !

You have reached the end of this post. ko-fi

No Comments Yet