Outputting Formatted Strings

The print Function

The print function takes multiple arguments and concatenates them:

a = 2
b = 3
print("The sum of", a, "and", b, "is", a + b)
The sum of 2 and 3 is 5

Notice that a space (" ") is added between each argument, or you can specify a different “separator” with the sep= parameter.

To add a period at the end, use the end= parameter. Make sure to include a newline (\n):

print("The sum of", a, "and", b, "is", a + b, end=".\n")
The sum of 2 and 3 is 5.

Since the plus (+) sign can also be used for string concatenation, it is possible to build the output message in the following manner:

a = 2
b = 3
print("The sum of " + str(a) + " and " + str(b) + " is " + str(a + b) + ".")

Using commas to separate arguments is more compact and, I think, more readable. It also avoids having to wrap the numeric variables in a str() conversion.

The format Function

The format function can be used with print to output a message with embedded variables.

a = 2
b = 3
print("The sum of {} and {} is {}.".format(a, b, a + b))
The sum of 2 and 3 is 5.

Note that the braces can be given a positional index ({0}, {1}) or a keyword ({name}, {time}, etc., following normal rules for variable naming) which allows you to reuse a parameter at different positions within the string.

If you intend to reuse the message statement, it is useful to assign to a variable:

msg = "The sum of {} and {} is {}."

a = 2
b = 3
print(msg.format(a, b, a + b))
The sum of 2 and 3 is 5.
c = 8
d = 7
print(msg.format(c, d, c + d))
The sum of 8 and 7 is 15.

In the past, students doing online searches for Python string formatting have sometimes discovered another way to insert variable values into a string:

"The sum of %d and %d is %d" % (a, b, a + b)

This is considered old style formatting, and you should not use it in this course.

References

Leave a Reply