String Formatting (.format()), online

Six activities your students do on their own devices. See who's finished, and their scores.

String Formatting (.format()) in one minute

What students need to know

{} placeholders are filled in order by the .format() arguments. :.2f formats a float to 2 decimal places.

{} is a placeholder — .format() fills it in with the argument. {} marks where the value from .format() gets inserted.

Mistakes students make

  • Missing parentheses and argument: .format(name) needs ().
  • Use curly braces {} for placeholders, not parentheses ().
  • f-strings use {curly braces}, not [square brackets].
  • One {} placeholder but no argument provided.

Discover other journeys with this module

What students will learn in this module

Every question in Module 32

Quick questions

  1. What does 'Hi {}'.format('Alice') return?A'Hi {}'B'Hi Alice'
  2. What does {} represent in .format()?ACurly braces to printBA placeholder for a value
  3. '{} + {} = {}'.format(2, 3, 5) returns?A'2 + 3 = 5'B'{} + {} = {}'
  4. What's the advantage of .format() over + concatenation?AHandles mixed types automaticallyBIt's faster
  5. What does f'Hi {name}' do?AInserts the variable name's valueBPrints 'Hi {name}'

Key terms

Students type the meaning of:

  • {}
  • .format()
  • f-string
  • {:.2f}

Match the pairs

'{} and {}'.format('a')Match it to what it does
'{name}'.format('Alice')Match it to what it does
'{} is {}'.format('Bob', 15)Match it to what it does
'{:.2f}'.format(3.14159)Match it to what it does
print('{} + {} = {}'.format(1,2,3))Match it to what it does
print('{name}'.format(name='Ali'))Match it to what it does

Fill in the blanks

  1. name = 'Alice'
    print('Hello __'.format(name))
  2. age = 15
    print('Age: {}'.______( age))
  3. name = 'Bob'
    print(_'{name} is here')
  4. price = 9.99
    print('{____}'.format(price))
  5. a = 5
    b = 3
    print(f'{a} + {b} = {a _ b}')

Spot the error

Question 1

Aname = 'Alice'Bage = 12Cmsg = 'Hello {}'.formatDprint(msg)

Question 2

Aname = 'Alice'Bage = 12Cmsg = 'Hi (name), age (age)'.format(name='Alice', age=12)Dprint(msg)

Question 3

Aname = 'Alice'Bage = 12Cmsg = f'Hi [name], age [age]'Dprint(msg)

Question 4

Aname = 'Alice'Bage = 12Cmsg = 'Hello {}'.format()Dprint(msg)

Question 5

Atemplate = '(name) and (age)'Bname = 'Alice'Cmsg = template.format(name='Alice', age=12)Dprint(msg)