In this Python snippet post we're going to take a closer look at a function we've all been using since we wrote our very first "Hello, World!" in Python. Of course, I'm talking about
print(1, 2, 3, 4, 5) # 1 2 3 4 5
Note that this is not the same as us passing in a single tuple of values like this:
print((1, 2, 3, 4, 5)) # (1, 2, 3, 4, 5)
Instead, each value is a separate argument, and items are separated by commas.
sep keyword only parameter.
sep accepts a string as a value, and this string will be placed between each item in the printed result.
print(1, 2, 3, 4, 5, sep=", ") # 1, 2, 3, 4, 5 print(1, 2, 3, 4, 5, sep=" | ") # 1 | 2 | 3 | 4 | 5
end which allows us to configure what gets placed at the end of the print line. The default value is
"\\n", which is the newline character. This is why each
Perhaps we want a blank line after a particular print. We could achieve this like so:
print(1, 2, 3, 4, 5, sep=" | ", end="\n\n")
Here we add two newline characters on the end of the
Another use for
end is to remove the line break from the end of the
The final piece of configuration we're going to look at is the
file parameter. The default value for
sys.stdout, but we have a couple of interesting options available to us.
The first is
sys.stderr, which allows us to print a line as though it were an exception. This means that it's coloured red, and therefore stands out from the normal
import sys print("You messed up!", file=sys.stderr)
Another interesting option is printing to just any old file. In order do do this, we have to use the
open function as usual to generate a file object. I'd recommend using a context manager for this:
with open("example.txt", "w") as f: print("Here is some file content", file=f)
Generally speaking, you're going to want to use the
write method instead for something like this, but
That's it for this snippet post. I hope you learnt something new, and if you're interested in learning more about
If you're just getting started with your Python journey, you might want to check out our Complete Python Course! We'll get you writing awesome Python in no time!
You should also think about subscribing to our mailing list to stay up to date with all our content, and get regular discount codes for all our courses.