Suppose you need to print two or more expressions (or just strings) in Python.
You can either use the comma operator, like so:
print("Hello,", "world!")
Or the plus operator, like so:
print("Hello," + " " + "world!")
What’s the difference between them, and which should you use in your code? If you found yourself wondering about the same, it’s good that you stopped by. Because this is exactly what you and I will be discussing, with code and without the B.S., in the remainder of this guide.
The Comma (,
) Operator
In Python, the comma (,
) operator allows you to print two or more expressions by outputting them one after the other and adding a blank space between each pair.
Let’s look at an example:
print("Hello,", "world!")
# Hello, world!
Notice that, when using the comma (,
) operator, the print
statement adds a blank space between each expression when printing the result.
Blank space is the default separator. However, you can change it to anything else you want with the help of the sep
argument.
Here’s how this works:
print("Apples", "Bananas", "Tomatoes", sep="; ")
# Apples; Bananas; Tomatoes
The Plus (+
) Operator
In Python, the plus (+
) operator allows you to print two or more expressions by concatenating them into a string.
For example:
print("Hello," + "world!")
# Hello,world!
Since the plus (+
) operator concatenates the strings as they are, they’ll be squished together unless you explicitly include a leading space as part of the print
statement:
print("Hello," + " " + "world!")
# Hello, world!
print("Hello, " + "world!")
# Hello, world!
print("Hello," + " world!")
# Hello, world!
Which Is Better?
These two operators lead to the same result, but as far as how the code is interpreted goes, they are completely different. This begs the question: which should you use?
You’d think that the comma (,
) operator is better because it doesn’t concatenate the expressions together into a single string (remember, it prints them one after the other and inserts a separator between each adjacent pair), but you’d be wrong!
As a StackOverflow user demonstrated, all other things being equal, there’s only benefit to using the comma (,
) operator over the plus (+
) operator when you need to print many expressions together on the screen. Of course, there might be other considerations at play here — like your team’s coding convention.
If you’re looking for my two cents, I think that the comma (,
) operator is more practical because it allows you to define a separator once and then it inserts it for you. With the plus (+
) operator, you have to manually insert the separator between each pair (or construct a function that does this for you, adding unneeded complexity).