What is the output of this code snippet?
# The number of units per player units = {} units['Alice'] = 10 units['Bob'] = 15 x = 'Alice' y = 'Bob' d = units['Bob'] - units['Alice'] print('{} has {} units less than {}'.format(x,d,y))
The string format function is a useful feature that is new in Python 3. Use it to programmatically insert variable values into the string. Without the format function, you must break the string into a series of smaller substrings and concatenate them. For example, the last line would be:
print(x + ' has ' + str(d) + ' units less than ' + y).
The format function is more convenient. When writing the string, you can use the curly brackets '{}'
and fill in the values later at the indicated position. It also takes care of the conversion from numerical values to strings.
Are you a master coder?
Test your skills now!
Related Video
Solution
Alice has 5 units less than Bob

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.