Daily Python Puzzle: String Formatting

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

 

Leave a Comment