Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Why are commas not needed for modulo string formatting when printing?
Parent
Why are commas not needed for modulo string formatting when printing?
Suppose I have two variables that are called animal
and age
, and print them as a string in the console like so:
animal = "giraffe"
age = 25
print("A %s can live up to %d years" %(animal,age))
Why shouldn't there be a comma between the string and the %(animal,age)
part? Does Python automatically detect that it needs two parameters to execute?
Post
It is, as you said, an operator so it doesn't make any sense to place a comma somewhere between the operator and the two operands. The first operand is the template string, and the second operand is the tuple with the values to format into the template string. The print()
function gets one argument — the result of the formatting operation.
Maybe it helps to bind both operands to names, so the expression becomes a bit simpler:
animal = "giraffe"
age = 25
template = "A %s can live up to %d years"
values = (animal, age)
print(template % values)
The %
operator is syntactically no different than other binary operators like +
or /
and so on.
1 comment thread