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 :
#Hello
#World
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="y\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=" ")
time.sleep(1)
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)
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 !
Top comments (8)
In section 2, you have the following snippet:
which you say outputs:
Shouldn't the snippet instead be:
In this case, I wanted every line to end with a
y
character rather than ay
character on a newline.Anyways, playing around with those will help grasp it better.
Yes, that's my point. Your code currently does not end every line with a
y
.Your
end
for the second print is just\n
. It is missing ay
in it.You'll have to include the
end="y"
un every print statement . In the second print statement you wrote, you didn't include theend="y"
and that's why you didn't get they
at the end of it.I'm aware. This is your code, not mine. Your code does not currently include
end="y\n"
for the second line, justend="\n"
. However, you then show output with every line ending in ay
: i.imgur.com/haIqpYx.pngOh thanks π€¦ I hadn't notice it . I'm really sorry for this
No problem! Happy to help!
Great article, never knew about these stuff