How to Print an Iterable With a Custom Delimiter in Python
Better debugging
It’s easy to take for granted simple tasks such as printing. You’ll very quickly find out about the PrettyPrint module that comes natively in Python and just needs a simple import.
However, there’s a lot more you can do with a simple print() function. In this piece, we’ll go over a technique for printing iterables with a custom delimiter. We’ll get outputs such as:P y t h o n
P,y,t,h,o,n
P
y
t
h
o
n
Let’s get to it!
Splat Operator
While it’s not officially known as the splat operator — a term taken from Ruby — the asterisk symbol, when used in a function call, will unpack an iterable.print(*"Python") # P y t h o n
For more information on the * or ** operators, check out a previous piece entitled What Are *args and **kwargs in Python?
The sep Parameter
Unbeknownst to many, the print() function actually has optional parameters that modify its behavior. By default, the sep parameter is set to a non-breaking space.
We can see the effect of sep by printing two strings, once without passing an argument and the other with a custom separator.print("Hello","World") # Hello World
print("Hello","World",sep=":") # Hello:World
The Solution
To print our iterable with a custom delimiter, we’ll combine the splat operator and pass a custom delimiter.msg = "Python"
print(*msg, sep=",") # P,y,t,h,o,n
If we want to print each character line by line, use a newline character as the custom separator.
This technique is not limited to strings. Use the same combination if you want to print a list, tuple, or set.
Conclusion
What are some of your favorite real-world use cases for either unpacking iterables or using a custom separator? Thanks for reading and I appreciate the support.