Let’s check out some exercises that will help you understand .format() method better.

Exercise 1-a: Python format method of strings

Place a curly bracket "{}" in the appropriate place and fill inside .format()'s parenthesis so that "Hello!, Name" is printed.


Although it might look slightly weird in the beginning, .format() method is an extremely convenient method for string class objects.

The syntax is:
“{} {}”.format(value1, value2…)

As curly brackets get replaced with values inside the parenthesis.

str = "Hello!, {}".format(name)

 

Exercise 1-b: Format method to type a number

Using a string and .format() method print the number: 1 only.


Although it might look slightly weird in the beginning, .format() method is an extremely convenient method for string class objects.

The syntax is:
“{} {}”.format(value1, value2…)

As curly brackets get replaced with values inside the parenthesis.

print("{}".format(1))

Exercise 1-c: Format method to fill multiple values

Now using a string and .format() method and three curly brackets, print the numbers: 1, 2, 3 each separated with a comma.


Although it might look slightly weird in the beginning, .format() method is an extremely convenient method for string class objects.

The syntax is:
“{} {}”.format(value1, value2…)

As curly brackets get replaced with values inside the parenthesis.

str = "{}, {}, {}".format(1, 2, 3)

Exercise 1-d: Format method for multiple values (more meaningful example)

Fill in the values for months, weeks and days accordingly.


Although it might look slightly weird in the beginning, .format() method is an extremely convenient method for string class objects.

str = "One year has {} months, {} weeks and {} days.".format(12, 52, 365)

 

Exercise 1-e: Format method w/ value position mapping

You can also use indexing inside your curly brackets so that you will decide the position instead of a default order.


By filling inside the curly brackets, make sure each bracket is matched to the appropriate value.


You can also use indexing inside your curly brackets so that you will decide the position instead of a default order. For instance:

“{2} {1} {0}”.format(“a”, “b”, “c”)
will result in:
“c b a”

str = "One year has {2} months, {0} weeks and {1} days.".format(52, 365, 12)

Exercise 1-f: Mapping exam scores with Format method

Fill inside .format()'s parenthesis so that it matches the correct values.


You can also use .format() with a string variable such as:
str.format()

str=str.format(John, Ann, Ally)