Python features image

Using Python 3 String Formatters

Introduction

The str.format() method in the string class of Python lets you do a variety of value formatting and substitution. Positional formatting and concatenation of elements within a string are done using string formatters in Python 3.

In this tutorial, you will learn about the common uses of string formatters in Python. Formatting the strings will help you write more user-friendly and comprehensive programs.

Using Formatters

Python 3 formatters work by replacing the fields or placeholders. You can define the fields/placeholders using the curly braces {}  into the string. And after calling the str.format() method the values you are passing as arguments will be concatenated in the place of placeholders.

Let’s try to print a string using a formatter:

In this example, you can see the string is made up of a sentence with a pair of curly braces. This pair of curly braces will act as a placeholder:

After that, the str.format() method is added and the value of integer 8 is passed as an argument to the method. Doing this will replace the value of 8 with the curly braces. You can also provide a variable as an argument, which is equal to the value of a string with formatter placeholders:

In this example, you were able to concatenate the string “python programming” with another string, that replaced the curly braces in the original string. As you have seen in the above examples, you can use curly braces as placeholders to pass the values using str.format() method.

Formatters with Multiple Placeholders

You can add multiple pairs of curly braces to include more than one variable for substitution. You can do this in a similar fashion as shown in the example below:

Here, adding one more pair of curly braces into the original string will give you two placeholders to modify. After that, passing two strings into the str.format() method will result in the replacement of the braces with the strings. Ensure that the strings inside the str.format() method are separated by a comma. Using a similar syntax, even more substitutions can be added:

The example2_string has 4 pairs of curly braces that can be substituted by variables. Afterward, 4 arguments are being passed to the str.format() method. These values are combinations of integer and strings separated by a comma.

Positional Arguments in Formatters

You can see from the above examples, any number of curly braces that are empty without parameters will be replaced in sequential order by the str.format() method of Python. Thus,  for the below example with two empty curly braces, the values passed as arguments will result in:

The first set of curly braces is being replaced with the string value of “car,” and the subsequent set of curly braces is being replaced with the string value of “bike.” The two values which are in the method are:

These are actually the tuple data type. Each of the individual values in the tuple is accessible using the index number, this index starts with the number 0. You can write the index numbers inside the curly braces as shown below:

You will get a similar output as to what you would get even if didn’t put the index numbers. The reason for this is the passing of the values in sequential order:

Now, interchanging the index numbers with respect to the placeholders will reverse the values passed to the method:

#Note:
If you have index positions 0 and 1, and you are calling index number 2 in the method, then essentially it is trying to access a non-existent/out-of-range value. So in this case you will get an error message as below:

As evident by the above error, you can see trying to access the value other than the index numbers 0 and 1, in this case, “2” results in an index out of range error.

Reordering with Multiple Formatters

To get more understanding about the reordering of formatters and how to pass more values to them, let’s manipulate a string with three placeholders:

Passing the values without the index numbers into the str.format() method will concatenate the values into the original string in a sequential manner. These string values in the tuple have the index numbers as shown below:

#Note

“young” “impatient” “inspiring”
0 1 2

Now let’s try to modify the order of values in the string using the index numbers:

Since the index numbers are in decreasing order from 2, the value of “inspiring” will come first. Other index numbers determine how the values of arguments to str.format() method will appear within the string.

Keyword Arguments in Formatters

Apart from the index numbers i.e. positional arguments, you can also provide keyword arguments. You will have to place a keyword inside the curly braces and then you can assign the values:

In the above example, you can see the keyword “mr” being used instead of the positional arguments used until now. You can pass the keyword argument along with other positional arguments. Also, you can move around the keyword arguments to change their position in a similar manner as previous examples:

Using the keyword arguments in combination with positional arguments, will grant you more control in formatting and manipulating the strings.

Specifying the Conversion Type

There are a number of parameters that you can use within the curly braces of the syntax. Let’s see the next code syntax {field:coversion_type}. In this syntax “field” determines the index number of argument to str.format() method, and the conversion_type determines the conversion code for the data type you are using in the method.

The conversion type is a single character code in Python which determines the data type. You will use some common data types in upcoming examples. There are codes for the data types. Some of these codes are, d for integers(with base 10), f for floating decimal numbers, and s for a string. More information about Python 3 format specifications can be found here.

In the below example let’s modify the integer to float through the str.format() method using the f conversion argument:

In the example above, you will see two different curly braces, one with syntax {field:conversion_type} and one only with {field}. And as shown in the output a lot of numbers after a decimal point are printed. Limiting the number of digits in the output is possible by specifying the precision.

Specifying the Precision

Since the precision of more than 2 decimal points is not required in the example, let’s limit the numbers after the decimal point to 2 by providing a prefix of .2 to the conversion_type argument:

Similarly, if you want more decimal places, the example can be reformed like:

#Note
Changes in the precision will round off the number after the decimal.

Since we cannot convert the float to an integer, explicitly doing so using the d conversion type will result in an error:

If you need to print with no decimal places, you can use 0 before the f conversion type:

This change will essentially limit the number of digits after the decimal point instead of converting float to an integer.

Padding Variable Substitutions

The placeholders are essentially replacement fields. They are used in manipulating the field size into adding more space or increasing the size using some extra parameters. This is especially useful if you are dealing with visual data. Thus, to provide the field size in the terms of a number of characters, you can put the size after : (colon) in the curly braces:

In the output, you will see the number 2 has a field size of 6, and the string “cars” has a field size of 8.

Aligning the Strings

As you can see in the output the default justification for the number is right and for string it is left. Modifying the alignment code after the colon can change the alignment. Three commonly used codes for alignment are, “<” for left alignment, “>” for right alignment, and “^” for centering the text in the field.

Let’s try centering the number and right alignment for the string from the above example:

After the alignment changes, you should see the number 2 is centered in the field and the string is aligned to right, keeping the space to the left in the field. Python fills the spaces left in the field by whitespace characters by default. Changing the whitespace character is pretty easy, you can change it to any other character by specifying the required character directly after the colon:

Here, since we did not specify the index number in the curly braces the string passed to str.format(). The method takes the index 0, and the use of “#” instead of whitespace characters fills the space with “#”. Use of “^” centers the string and a field size of 10 characters makes space of 2 characters on each side of the string.

The combination of parameters you have used until now looks like this:

In this example, the parameters inside the curly braces are index field number (0), size of the field (8), and the number of places after decimal point(2), and lastly the type float which is indicated by f.

Using Variables

Until now, you have been passing arguments like strings floats to the str.format() method. In a similar manner, you can also pass variables through the method:

The original string and the argument to the str.format() method both can be variables, as shown in the example:

The substitution of variables for the construction of formatter syntax makes it easy for dealing with taking some input from other programs/users and using those values.

Organizing Data Using Formatters

The formatters can come in handy for organizing a large piece of data in a visually pleasing manner. In case of display of some information to the end-user from a company database, use of formatters can make wonders in the presentation of the data.

As an example, let’s create a loop in Python that will print squares and cubes of numbers from 1 to 10:

The output may seem organized, but the numbers are going into other columns. In the case of a larger piece of data, this can cause issues in readability.

Using the formatters can provide more space between the numbers in the output:

After providing the field size and conversion to integer type (d) the output looks like this:

This arrangement seems to be working for the current data. For managing even more amount of data and consistent columns the same field size can be provided:

The alignment of the columns can also be manipulated using the <,>,^ for text, type of the data can also be formatted to f to show data with decimal places. Furthermore, many more manipulations are possible to ensure the display of data in a proper manner.

Conclusion

Formatters can provide a compelling and efficient way to manipulate strings and organize the data in a visually appealing manner. They provide a simple way for variable substitutions into a string and are incredibly useful to make output convenient.

Now that you have learned about string manipulation in Python, here are some more tutorials that will get you started on utilizing Python:

Happy Computing!