get consultation

Formatting

The format method is used to format strings.

Format

The {} is used as a placeholder for data. The format method contains a list of strings or numbers that is used to replace the {}, in order.

format.py
# you can use format to format strings
name = 'Steve'
color = 'Blue'

print('My name is {} and my favorite color is {}'.format(name, color))

Output:

My name is Steve and my favorite color is Blue

print with f

You can also use the f in a print to format a string.

print_f.py
name = 'Steve'
color = 'Blue'
print(f'My name is {name} and my favorite color is {color}')

first_name = 'Joe'
last_name = 'Smith'
name = f'{first_name} {last_name}'
print(name)

Output:

My name is Steve and my favorite color is Blue
Joe Smith

Links

Exercises (5 mins)

  1. Complete the following program.

    # 1. input name with 'Enter name:'
    
    # 2. input favorite_food with 'Enter favorite food: '
    
    # 3. print My name is {name} and my favorite food is {favorite_food} with format
    

    Output:

    Enter name:Steve
    Enter favorite food: Burrito
    My name is Steve and my favorite food is Burrito
    
  2. Complete the following program.

    # madlibs
    
    # Enter an adjective
    # Enter a verb
    # Enter another verb
    # Enter a famous person
    
    madlib = f'Computer programming is so {adjective}! It makes me so excited all the time because I love to {verb1}. Drink water and {verb2} like you are {famous_person}'
    
    print(madlib)
    print('Done.')
    

    Output:

    Enter an adjective:cool
    Enter a verb: skydive
    Enter another verb: jump
    Enter the name of a famous person: Elon Musk
    Computer programming is so skydive! It makes me so excited all the time because I love to skydive. Drink water and jump like you are Elon Musk