Note: The following code is valid only for Python 3.0 and up.
If you’ve gone through even one tutorial of any programming language, you know the first thing you do is print “Hello World” to the console. Python’s way of doing that is, of course, print(). And it’s as simple as typing the line
print("Hello Word") # Hello World
Tutorial over, right? Well, no. Turns out print() has some hidden use cases.
The print function takes multiple objects so you can do some goofy things like:
print("my", "name", "is", "Austin") # my name is Austin
This returns my name is Austin because print’s default separator is a space(‘ ‘). This can easily be changed though by adding the keyword argument sep after the things to print. In the example of:
print("my", "name", "is", "Austin", sep="") # mynameisAustin
the output mynameisAustin isn't pretty, but it is functionality that could come in handy.
There is also the option of using the keyword argument end, which defaults to a line break(“\n”).
print("my", "name", "is", "Austin", sep=",", end="!") # returns: my,name,is,Austin! # you can actually use any valid string in the keyword argument end
Now we’re done, right? Nope. There’s more goodness packed into this function.
What if you wanted a log of everything you printed? Well, print() already has that functionality. All you need to do is use the keyword argument file. Let’s say I wanted a .txt document as the output of the last print statement:
with open("text.txt", "w") as text: print("my", "name", "is", "Austin", sep=",", end="!", file=text) # this take the output as before (my,name,is,Austin!) and outputs it # into text.txt
(More to come on the open() function, it's got some neat things to explore as well)
This is powerful alternative to printing everything to the console and can help log potential errors while debugging.
Like many things in programming, print() is something we often take for granted without really looking at it too deeply. Now that you’ve seen what print can actually do, I hope that it will help you in your development.
Thanks for reading!