DEV Community

Josias Aurel
Josias Aurel

Posted on • Edited on

Python print() and beyond

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
Enter fullscreen mode Exit fullscreen mode

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 : 
#Hello
#World
Enter fullscreen mode Exit fullscreen mode

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

name = "Samson"
print(f"Hello {name}")
# Output : Hello Samson
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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="y\n")
Enter fullscreen mode Exit fullscreen mode

We get the following output

Hello Jamesy
How are you doingy
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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=" ")
    time.sleep(1)
Enter fullscreen mode Exit fullscreen mode

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)
    time.sleep(1)
Enter fullscreen mode Exit fullscreen mode

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

Top comments (8)

Collapse
 
ntchambers profile image
Nicholas Chambers

In section 2, you have the following snippet:

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

which you say outputs:

Hello Jamesy
How are you doingy
Enter fullscreen mode Exit fullscreen mode

Shouldn't the snippet instead be:

print("Hello James", end="y\n")
print("How are you doing", end="y\n")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
josiasaurel profile image
Josias Aurel • Edited

In this case, I wanted every line to end with a y character rather than a y character on a newline.
Anyways, playing around with those will help grasp it better.

Collapse
 
ntchambers profile image
Nicholas Chambers • Edited

Yes, that's my point. Your code currently does not end every line with a y.

~ 🌲 python3
Python 3.9.0 (default, Nov 30 2020, 15:21:09)
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello James", end="y\n")
Hello Jamesy
>>> print("How are you doing", end="\n")
How are you doing
Enter fullscreen mode Exit fullscreen mode

Your end for the second print is just \n. It is missing a y in it.

Thread Thread
 
josiasaurel profile image
Josias Aurel

You'll have to include the end="y" un every print statement . In the second print statement you wrote, you didn't include the end="y" and that's why you didn't get the y at the end of it.

Thread Thread
 
ntchambers profile image
Nicholas Chambers

I'm aware. This is your code, not mine. Your code does not currently include end="y\n" for the second line, just end="\n". However, you then show output with every line ending in a y: i.imgur.com/haIqpYx.png

Thread Thread
 
josiasaurel profile image
Josias Aurel

Oh thanks 🤦 I hadn't notice it . I'm really sorry for this

Thread Thread
 
ntchambers profile image
Nicholas Chambers

No problem! Happy to help!

Collapse
 
ashwin_vinod profile image
Ashwin Vinod

Great article, never knew about these stuff