You are already familiar with basic string concatenation. It's easy to build a longer string by gluing together shorter pieces with the plus sign (+). However, you will often want to build longer strings that have very specific spacing or numeric formatting. In this lesson, you will learn how to use the str.format() function to gain great control over formatted output.

Introducing str.format()
The Python str.format() function is a very flexible and useful tool. You can use it to build all kinds of specific strings from a variety of input values. When calling this function, be sure to include the "str." prefix on the front of "format".

The str.format() function takes one or more parameters inside the parentheses. The first parameter should be a "format string". This string sets up the overall structure of the output. The format string is then followed by one or more values that you want to insert into the string. The entire function will return a new string that has been built from the format string and input values. The general pattern is shown below.

result = str.format(format,value0,value1,...)
Copy
The most interesting part of str.format() is the format string. The format string is very powerful and has many formatting options. A basic format string will include sets of curly braces {} wherever input values are supposed to be inserted.

Consider the format string "My name is {}. Happy to meet you, {}.". There are two sets of curly braces, so the str.format() function will expect you to provide two values for those locations. The example below uses this format string and two input values to build an output message that is printed on the screen. Try it to see the results.

Try It Now


Hard-coding values like "Wrascal" and "Wrabbit" in the paramter list is rarely done in real programs. You could more easily just code those values into the final string.

result = "My name is Wrascal. Happy to meet you, Wrabbit."
Copy
More commonly, you will use variables as the parameters. The contents of those variables might be set somewhere else or even change based on user input. This allows you to create dynamic output! Run the program below and type in your own creative names to see the output.

Try It Now


It is possible to call this format() function directly on a format string with a slightly different syntax. Instead of writing "str.format()", the "str" part is replaced by the format string itself. Then, inside the parentheses, you simply list the values. The example below should produce the same output as our first example.

Try It Now


We won't usually write code like this in our lessons. However, you may see this pattern elsewhere, so we want to make sure you understand the different patterns.

Using Placeholder Numbers
When curly braces {} appear within a format string, it means a value will be inserted in that location. By default, the first value will go to the first set of curly braces, the second value will go to the second set, and so on.

Default Value ordering

However, you can add numbers within the curly braces, and that means the matching value will be placed in that location, regardless of the overall order or number of curly braces. The numbers are zero-based, meaning {0} represents the first value, {1} matches the second value, and so on. The example below adds placeholder numbers and reverses their order within the output. The second value appears first at {1}, and the first value is added later at {0}.

Try It Now


When you run this code, you'll see "Wrabbit" come first and then "Wrascal" in the second location.

Curly braces with placeholder numbers

You can even use numbered placeholders to repeat values within the output. A format string containing "{0} {0}" would display the first value twice in the output. Try editing one of the above code samples and test a repeated value.

Width, Truncation, and Alignment
So far, the strings produced from str.format() don't look much different than what you'd get using the plus sign (+) and simple concatenation. str.format() will really start to shine when you begin giving special formatting guidance to the placeholder curly braces.

Special formatting options are added inside the curly braces, starting with a colon placed to the right of the number "{0:}". After the colon, you can add a number that sets the specific output width for that string field. For example, if you wanted each of the names in our greeting example to be at least 10 characters wide in the output, we would add ":10" inside the curly braces as shown below. The result will contain at least 10 characters, padded with spaces where needed. Run the code below to see the result.

Try It Now


The width setting will not limit longer strings, so if you run the above example again and type in a long name, the full name will be shown. If you want to truncate (clip) a longer string after a certain number of characters, you can add a dot (.) and then the maximum length afterward. Let's limit our 10-character side strings to no more than 10 characters with ":10.10". When you run this example, you will notice the second name is limited to 10 characters, "Christophe".

Try It Now


You will notice that a short string will start on the left side of a wider area, with spaces added to the right. You can control this alignment with one of three special characters added right after the colon.

Format Symbol Description Alignment Example
< The left angle bracket produces left alignment Left
> The right angle bracket produces right alignment Right
^ The carat centers text in the available width Center
Let's try out each of these alignment controls! The example below will display three values with left, center, and right alignment in fields that are 20 spaces wide.

Try It Now


The format width, truncation and alignment controls can be combined to produce nicely formatted columns like you might see in a spreadsheet. You'll get a chance to demonstrate these controls in the exercise at the end of this lesson.

Formatting Numbers
What happens if one of your input values is an integer or floating point number? You can control the number of decimal points and other numeric properties by adding one of the following letters to the end of the expression inside the curly braces.

Type Symbol Description Example
d Displays a regular integer 150000
, Displays a number with a comma thousands separator 1,500,000
e Displays a floating point number in scientific notation 3.141590e+00
f Displays a floating point number in regular fixed-point notation 3.141590
g Displays a number in some format that is chosen based on the type and size of the number 3.14159
% Converts the number to a percentage and displays with a percent sign (%) 75.000000%
The following example code will let you experiment with each of these symbols. Run the code to see the results, and then change some of the numbers to see how the output also changes. Notice that, by default, numbers are right-aligned in the available width.

Try It Now


There are many more format options beyond the basics that we've shown in this lesson! You can control the number of output digits, for example, the same way you limit the maximum length of strings. For more details on advanced formatting options, please see the official Python document for format strings.

1. In the format string, what set of symbols is used to identify a location where a value is inserted?
2. How do placeholder numbers allow you to control where values appear in the output?
3. How do you set the minimum width of an input value?
4. How to you set the maximum width of an input value?
5. How do you set the alignment of an input value?
6. What options do you have for formatting numeric values? How does each work?

1. Curly braces {} are used to identify a location where a value is inserted in the format string.

2. Placeholder numbers allow you to control where values appear in the output by specifying the index of the value to be inserted. The numbers are zero-based, so {0} represents the first value, {1} represents the second value, and so on.
3. To set the minimum width of an input value, you can add a colon (:) followed by the desired width inside the curly braces. For example, "{0:10}" will set the minimum width of the first value to 10 characters.
4. To set the maximum width of an input value, you can add a dot (.) followed by the maximum width inside the curly braces. For example, "{0:.10}" will truncate the first value to a maximum of 10 characters.
5. To set the alignment of an input value, you can add one of the three special characters (< for left alignment, > for right alignment, and ^ for center alignment) right after the colon. For example, "{0:<10}" will left align the first value within a field of width 10.
6. The options for formatting numeric values are as follows:
- d: Displays a regular integer.
- ,: Displays a number with a comma thousands separator.
- e: Displays a floating point number in scientific notation.
- f: Displays a floating point number in regular fixed-point notation.
- g: Displays a number in a format chosen based on the type and size of the number.
- %: Converts the number to a percentage and displays it with a percent sign (%).