× Lesson 1 Lesson 2 Lesson 3 Lesson 4 Lesson 5 Lesson 6 Lesson 7 Lesson 8 Lesson 9 Lesson 10 Lesson 11 Lesson 12 Lesson 13 Lesson 14 Lesson 15 Lesson 16 Lesson 17 Lesson 18 Lesson 19 Lesson 20 Lesson 21 Lesson 22 Lesson 23 Lesson 24 Lesson 25 Mini Lesson 1 Mini Lesson 2 Mini Lesson 3 Mini Lesson 4 Mini Lesson 5


Lesson 7 - String formatting

String formatting involves strings, which have been discussed previously, and data to insert into the string.

There are two ways of accomplishing this, the first is the .format(). The basic syntax is:


You can of course put in string you would like in the quotations, however the curly brackets are where the variable would be placed in the string. You can have multiple sets of curly brackets as well. The syntax for that would look like this:

"{} {} {}".format(variable1, variable2, variable3)

One more thing to note for now is that you can put in a data type in the parenthesises, you aren't limited to only putting variables in the parenthesises. I challenge you to use the .format() method to print out the following phrase: 'Hello, my full name is (your full name)! Nice to meet you!' You can either put the string for you name in the .format() directly, or set your full name equal to variables and then using the .format().

The second type of string formatting is the % sign. The syntax for this is relatively the same. Here's an example:

'The first 10 letters of the alphabet are: %s' % 'abcdefghij'

Notice the %s next to the %, as the data type that replaced the % was a string, we had to compensate for that by placing %s, and the same rule applies for integers, %d. For lists, you can use the %s. You can have multiple %'s. I once again challenge you to do the same thing as you did with the .format() method, printing 'Hello, my full name is (your full name)! Nice to meet you!'

Once you have finished the challenge move on to the next lesson!