# Chapter Three: Input and Output

## Lesson Three: String Formatting

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,...)

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 to the screen. Try it to see the results.

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 pattern.

### 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.

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.

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 afterwards. 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 SymbolDescriptionAlignment Example
<The left angle bracket produces left alignmentLeft
>The right angle bracket produces right alignmentRight
^The carat centers text in the available widthCenter

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 widthtruncation 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 SymbolDescriptionExample
dDisplays a regular integer150000
,Displays a number with a comma thousands separator1,500,000
eDisplays a floating point number in scientific notation3.141590e+00
fDisplays a floating point number in regular fixed-point notation3.141590
gDisplays a number in some format that is chosen based on the type and size of the number3.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.

https://docs.python.org/3/library/string.html#formatstrings

Work with Me: High Score Columns

Let's return to our example table of high scores, which we've previously printed in simple formats. In this exercise, you are going to take advantage of the str.format() function to neatly organize the name and score values into fixed-width columns. Your goal is to produce output like the example below.

       High Scores
Player Name   High Score
---------------------------
Hunter             995
AAA              850

Each row with a player name and a player score is formed with a call to str.format(). Locate the bottom three rows in the code below and you will see part of the code already written for you, with statements in the following form:

print(str.format("",name1,score1))

We are calling str.format() and then passing the resulting string directly into the print() function. Each incomplete statement has an empty format string "", but already passes in the correct name and score values. All you need to do is add the curly braces and other symbols inside the empty format string to get the right output.

• The name value should be centered in an area that is 15 characters wide and limited to a maximum of 15 characters.
• The score value should be displayed in an area that is 10 characters wide and use a comma-separator for the thousands.
• You can add a single space between the sets of curly braces in the format string.

Make your edits in the code window below and run your code to verify the output.

Try It Now

Console

End of Lesson