Python Reference and Tutorials

 

String Formatting

Python

The print() function is used to display text and data to the terminal window (or standard output). It is a common operation in programs that involve user interaction. For example, consider the following code segment which extracts a measurement in feet and inches from the user and then computes and prints the equivalent measurement in meters.

feet = int(input("Enter feet: "))
inches = int(input("Enter inches: "))
meters = (feet * 12 + inches) / 39.37
print(feet, "feet and", inches, "inches is", meters, "meters")

If the user enters 5 and 2 for the two input operations, the result will be

\begin{screentext} 5 feet and 2 inches is 1.5748031496062993 meters \end{screentext}

The default behavior of the \code{print()} function is to display a floating-point value with as many decimal places as necessary to express But what if we don't want it to print all of those decimal places? Perhaps we only want to display the meters measurement to 4 decimal places.

\begin{screentext} 5 feet and 2 inches is 1.5748 meters \end{screentext}

To accomplish this task, we have to produce a formatted string that is then displayed by the \code{print()} function. Python provides two techniques for formatting strings. In this appendix, we review the version known as ``C-style'' formatting, the name of which comes from the fact that it was first introduced by the C programming language. Today, most major programming languages provide this style of string formatting.

\subsection*{String Formatting Operator}

To produce the output shown above, with the value of meters displayed to 4 decimal places, we can use the following print operation

\begin{srcCode} print("d inches is %1.4f meters" % (feet, inches, meters) ) \end{srcCode}

The argument passed to the \code{print()} function is the string formatting operation that will generate a formatted string. It consists of three parts

\begin{itemize} \item[] $\underbrace{\code{"\%d feet and \%d inches is \%1.4f meters"}}_\textnormal{format string}$ \ $\underbrace{\code{\%}}_\textnormal{format operator}$ \ $\underbrace{\code(feet, inches, meters)}_\textnormal{replacement values}$ \end{itemize}

The \textit{format operator} takes a \textit{format string} to the left and a collection (tuple) of \textit{replacement values} to the right. The format string is any string consisting of text and special \textit{field format specifiers} (indicated by a \verb$%$ sign). When the string formatting operation is performed, it will produce a duplicate copy of the format string but with each field specifier replaced by one of the replacement values.

\newpage In our example, the field specifiers within the format string

\begin{srcCode} "d inches is %1.4f meters" \end{srcCode}

will be replaced with the values of \code{feet}, \code{inches}, and \code{meters}, respectively, resulting in a new string that is then printed

\begin{screentext} 5 feet and 2 inches is 1.5748 meters \end{screentext}

\subsection*{Field Format Specifiers}

A field format specifier, which begins with a percent sign (\verb$%$) and ends with a specific character, indicates a field into which a data value will be displayed. The character used with the field specifier indicates the type of data to be formatted. The three most commonly used field specifiers are

\begin{center} \begin{tabular}{cc} \verb!%d! & integer
\verb!%f! & float
\verb!%s! & string
\end{tabular} \end{center}

In addition to the type of data to be formatted, we can also indicate the number of columns used to display the data within the field. For example, if we want to use 6 columns to display the feet and inches values, then we can change the \code{\%d} specifiers to that shown below

\begin{srcCode} print("%6d feet and %6d inches is %1.4f meters" % (feet, inches, meters)) \end{srcCode}

which results in both \code{feet} and \code{inches} being displayed within a field consisting of 6 columns (the \textvisiblespace\ symbol represents a blank space within the field)

\begin{itemize} \item[] \verb*$ 5$ \code{feet and} \verb*$ 2$ \code{inches is 1.5748 meters} \end{itemize}

By default, the data values will be right-justified within the indicated number of columns. To left-justify the data, we use a negative column width. For example,

\begin{srcCode} print("%6d feet and %-6d inches is %1.4f meters" % (feet, inches, meters)) \end{srcCode}

will produce the following with \code{feet} right-justfied within 6 columns and \code{inches} left-justified within 6 columns

\begin{itemize} \item[] \verb*$ 5$ \code{feet and} \verb*$2 $ \code{inches is 1.5748 meters} \end{itemize}

If the field width is not large enough to display the entire data value or if you omit the field width altogether, then the data value will be displayed using as many columns as necessary. Consider the following example

\begin{srcCode} print("The triangle has %2d sides." % (387)) \end{srcCode}

which results in value 387 spilling over the 2 columns specified by the \code{\%2d} field specifier

\begin{screentext} The triangle has 387 sides. \end{screentext}

%You have seen how to format integer values, but what about floating-point %values? In addition to specifying the total number of columns to use, we can also specify the number of decimal places to use when formatting a floating-point value by appending a decimal point and an integer value to the field width. Thus, in our original example,

\begin{srcCode} print("d inches is %1.4f meters" % (feet, inches, meters) ) \end{srcCode}

we indicate that the floating-point value \code{meters} is to be displayed using a field width of 1 column and 4 decimal places. Thus, the \code{meters} measurement is displayed as

\begin{screentext} 1.5748 \end{screentext}

The floating-point field specifier will automatically round the displayed results if the value of the next column (after the one to be displayed is $\ge 5$). For example,

\begin{srcCode} print("d inches is %1.8f meters" % (feet, inches, meters) ) \end{srcCode}

will result in

\begin{screentext} 5 feet and 2 inches is 1.57480315 meters \end{screentext}

The following table illustrates the results of additional field format specifier examples

\begin{center} \def\arraystretch{1.2} \begin{tabular}{|p{3in}|p{2.5in}|} \multicolumn{1}{c}{\bf Example} & \multicolumn{1}{c}{\bf Result}\\ \hline\hline \verb#"%7s" % ("March")# & \verb*# March#
\hline \verb#"%-7s" % ("March")# & \verb*#March#
\hline \verb#"%7s" % ("December")# & \verb*#December#
\hline \verb#"%-12dX%8d" % (750, 25)# & \verb*#750 X 25#
\hline \verb#"%10.3f" % (3.1415926535)# & \verb*# 3.142#
\hline \verb#"%10.6f" % (3.1415926535)# & \verb*# 3.141593#
\hline \verb#"%-10.3f" % (3.1415926535)# & \verb*#3.142 #
\hline \verb#"%8.0f" % (3.1415926535)# & \verb*# 3#
\hline \verb#"Result = %12.2" % (3.1415926535)# & \verb*# 3.14%#
\hline \hline \end{tabular} \end{center}

\subsection*{Column Formatted Output}

Formatted strings are necessary when constructing a table or report consisting of columns. For example, suppose we need to produce the following table from data extracted from a text file. It consists of the total sales per month for some product (the first five months in this example):

\begin{screentext} Month Units Sold Total Sales


January 150 12856.54 February 75 9481.00 March 225 32011.75 April 200 28489.00 May 168 19234.00 \end{screentext}

Since the table consists of 3 columns, one for the month name, one for the number of units sold per month and one for the total sales for the given month, we will need 3 field format specifies. Suppose we used the following format string for each row of the table

\begin{srcCode} print("d %1.2f" % (month, units, total)) \end{srcCode}

The results would look as follows:

\begin{screentext} January 150 12856.54 February 75 9481.00 March 225 32011.75 April 200 28489.00 May 168 19234.00 \end{screentext}

While all of the rows and the data is displayed, it's not aligned properly. To correctly produce this table, we must also specify the width of each column.

\begin{srcCode} print("%13s %9d %12.2f" % (month, units, total)) \end{srcCode}

Now, the results look as follows:

\begin{screentext}

     January        150      12856.54
    February         75       9481.00
       March        225      32011.75
       April        200      28489.00
         May        168      19234.00

\end{screentext}

Remember, by default, the data values are right-justified within the given number of columns. Here, the numeric values are aligned properly, but not the month names. We need to left-justify the month name within the first column

\begin{srcCode} print("%-13s %9d %12.2f" % (month, units, total)) \end{srcCode}

which now produces the correct results

\begin{screentext} January 150 12856.54 February 75 9481.00 March 225 32011.75 April 200 28489.00 May 168 19234.00 \end{screentext}

\endinput

Python
Print -- Recent Changes
Page last modified on February 15, 2016, at 11:22 AM