Skip to main content
Engineering LibreTexts

8.4: String Formatting

  • Page ID
    117574
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    Learning Objectives

    By the end of this section you should be able to

    • Format a string template using input arguments.
    • Use format() to generate numerical formats based on a given template.

    String format specification

    Python provides string substitutions syntax for formatting strings with input arguments. Formatting string includes specifying string pattern rules and modifying the string according to the formatting specification. Examples of formatting strings include using patterns for building different string values and specifying modification rules for the string's length and alignment.

    String formatting with replacement fields

    Replacement fields are used to define a pattern for creating multiple string values that comply with a given format. The example below shows two string values that use the same template for making requests to different individuals for taking different courses.

    Example 8.5: String values from the same template
        Dear John, I'd like to take a programming course with Prof. Potter.
    
        Dear Kishwar, I'd like to take a math course with Prof. Robinson.

    In the example above, replacement fields are 1) the name of the individual the request is being made to, 2) title of the course, and 3) the name of the instructor. To create a template, replacement fields can be added with {} to show a placeholder for user input. The format() method is used to pass inputs for replacement fields in a string template.

    Example 8.6: String template formatting for course enrollment requests

    A string template with replacement fields is defined below to create string values with different input arguments. The format() method is used to pass inputs to the template in the same order.

        s = "Dear {}, I'd like to take a {} course with Prof. {}."
    
        print(s)
        print(s.format("John", "programming", "Potter"))
        print(s.format("Kishwar", "math", "Robinson"))

    The above code's output is:

        Dear {}, I'd like to take a {} course with Prof. {}.
        Dear John, I'd like to take a programming course with Prof. Potter.
        Dear Kishwar, I'd like to take a math course with Prof. Robinson.
    
    Concepts in Practice \(\PageIndex{1}\): String template and formatting

    What is the output of print("Hello {}!".format("Ana"))?

    1. Ana
    2. Hello Ana
    3. Hello Ana!
    Answer

    c. "Ana" is substituted for the replacement field {} in the template and hence the output is "Hello Ana!" .

    Concepts in Practice \(\PageIndex{2}\): String template and formatting

    What is the output of print("{}:{}".format("One", "1"))?

    1. One1
    2. One:1
    3. 1:One
    Answer

    b. The two arguments are passed to the template "{}:{}" that outputs "One:1" .

    Concepts in Practice \(\PageIndex{3}\): String template and formatting

    What is the output of print("{}".format("one", "two", "three"))?

    1. one
    2. two
    3. onetwothree
    Answer

    a. The arguments for the format() function are passed in order and will be substituted for the replacement fields. Additional arguments may be ignored by the template and remain unused.

    Named replacement fields

    Replacement fields can be tagged with a label, called named replacement fields, for ease of access and code readability. The example below illustrates how named replacement fields can be used in string templates.

    Example 8.7: Season weather template using named replacement fields

    A named replacement argument is a convenient way of assigning name tags to replacement fields and passing values associated with replacement fields using corresponding names (instead of passing values in order).

        s = "Weather in {season} is {temperature}."
    
        print(s)
        print(s.format(season = "summer", temperature = "hot"))
        print(s.format(season = "winter", temperature = "cold"))

    The above code's output is:

        Weather in {season} is {temperature}.
        Weather in summer is hot.
        Weather in winter is cold.
    Multiple use of a named argument

    Since named replacement fields are referred to using a name key, a named replacement field can appear and be used more than once in the template. Also, positional ordering is not necessary when named replacement fields are used.

        s = "Weather in {season} is {temperature}; very very {temperature}."
    
        print(s)
        print(s.format(season = "summer", temperature = "hot"))
        print(s.format(temperature = "cold", season = "winter"))

    The above code's output is:

        Weather in {season} is {temperature}; very very {temperature}.
        Weather in summer is hot; very very hot.
        Weather in winter is cold; very very cold.
    
    Concepts in Practice \(\PageIndex{4}\): Named replacement field examples

    What is the output of print("Hey {name}!".format(name = "Bengio"))?

    1. Hey name!
    2. Hey Bengio
    3. Hey Bengio!
    Answer

    c. "Bengio" is substituted in the named replacement field associated with the tag name; hence, the output is "Hey Bengio!" .

    Concepts in Practice \(\PageIndex{5}\): Named replacement field examples

    What is the output of print("Hey {name}!".format("Bengio"))?

    1. Hey name!
    2. KeyError
    3. Hey Bengio!
    Answer

    b. Since the string template uses a named argument, inputs are only accepted through the corresponding keys. Hence, the code generates KeyError: 'name'.

    Concepts in Practice \(\PageIndex{6}\): Named replacement field examples

    What is the output of the following code?

    greeting = "Hi"
    name = "Jess"
    print("{greeting} {name}".format(greeting = greeting, name = name))
    
    1. greeting name
    2. Hi Jess
    3. Jess Hi
    Answer

    b. The greeting variable with value "Hi" is substituted for the greeting replacement field. The same is also done for the name replacement field and the name variable. The output is "Hi Jess" .

    Numbered replacement fields

    Python's string format() method can use positional ordering to match the numbered arguments. The replacement fields that use the positional ordering of arguments are called numbered replacement fields. The indexing of the arguments starts from 0. Ex: print("{1}{0}".format("Home", "Welcome")) outputs the string value "Welcome Home" as the first argument. "Home" is at index 0, and the second argument, "Welcome", is at index 1. Replacing these arguments in the order of "{1}{0}" creates the string "Welcome Home".

    Numbered replacement fields can use argument's values for multiple replacement fields by using the same argument index. The example below illustrates how an argument is used for more than one numbered replacement field.

    Example 8.8: Numbered replacement field to build a phrase

    Numbered replacement fields are used in this example to build phrases like "very very cold" or "very hot".

        template1 = "{0} {0} {1}"
        template2 = "{0} {1}"
    
        print(template1.format("very", "cold"))
        print(template2.format("very", "hot"))

    The above code's output is:

        very very cold
        very hot

    String length and alignment formatting

    Formatting the string length may be needed for standardizing the output style when multiple string values of the same context are being created and printed. The example below shows a use case of string formatting in printing a table with minimum-length columns and specific alignment.

    Example 8.9: A formatted table of a class roster

    A formatted table of a class roster

        Student Name              Major          Grade
        ----------------------------------------------
        Manoj Sara          Computer Science        A-
        Gabriel Wang     Electrical Engineering      A
        Alex Narayanan       Social Sciences        A+

    In the example above, the table is formatted into three columns. The first column takes up 15 characters and is left-aligned. The second column uses 25 characters and is center-aligned, and the last column uses two characters and is right aligned. Alignment and length format specifications controls are used to create the formatted table.

    The field width in string format specification is used to specify the minimum length of the given string. If the string is shorter than the given minimum length, the string will be padded by space characters. A field width is included in the format specification field using an integer after a colon. Ex: {name:15} specifies that the minimum length of the string values that are passed to the name field is 15.

    Since the field width can be used to specify the minimum length of a string, the string can be padded with space characters from right, left, or both to be left-aligned, right-aligned, and centered, respectively. The string alignment type is specified using <, >, or ^characters after the colon when field length is specified. Ex: {name:^20} specifies a named replacement field with the minimum length of 20 characters that is center-aligned.

    Alignment Type Symbol Example Output
    Left-aligned

    <

    template = "{hex:<7}{name:<10}" print(template.format(hex = "#FF0000", name = "Red")) print(template.format(hex = "#00FF00", name = "green"))

    #FF0000Red #00FF00green

    Right-aligned

    >

    template = "{hex:>7}{name:>10}" print(template.format(hex = "#FF0000", name = "Red")) print(template.format(hex = "#00FF00", name = "green"))

    #FF0000 Red #00FF00 green

    Centered ^

    template = "{hex:^7}{name:^10}" print(template.format(hex = "#FF0000", name = "Red")) print(template.format(hex = "#00FF00", name = "green"))

    #FF0000 Red #00FF00 green

    Table 8.2: String alignment formatting.
    Concepts in Practice \(\PageIndex{7}\): Specifying field width and alignment

    What is the output of the following code?

    template = "{name:12}"
    formatted_name = template.format(name = "Alice")
    print(len(formatted_name))
    
    1. 5
    2. 12
    3. "Alice"
    Answer

    b. The template specifies the minimum length for the name field to be 12, so len(formatted_name) is 12 .

    Concepts in Practice \(\PageIndex{8}\)

    What is the output of the following code?

    template = "{greeting:>6}"
    formatted_greeting = template.format(greeting = "Hello")
    print(formatted_greeting[0])
    
    1. H
    2. " Hello"
    3. Space character
    Answer

    c. The alignment and the field length specifications format the greeting field to be six characters in length and right-aligned. Therefore, the variable formatted_greeting will take value " Hello" , and character 0 of the string is a space character.

    Concepts in Practice \(\PageIndex{9}\)

    What is the output of the following code?

    template = "{:5}"
    print(template.format("123456789"))
    
    1. 56789
    2. 123456
    3. 123456789
    Answer

    c. The field length specification enforces the minimum length of the string. Inputs that are longer than the specified minimum length will not be modified.

    Formatting numbers

    The format() method can be used to format numerical values. Numerical values can be padded to have a given minimum length, precision, and sign character. The syntax for modifying numeric values follows the {[index]:[width][.precision][type]} structure. In the given syntax,

    • The index field refers to the index of the argument.
    • The width field refers to the minimum length of the string.
    • The precision field refers to the floating-point precision of the given number.
    • The type field shows the type of the input that is passed to the format() method. Floating-point and decimal inputs are identified by "f" and "d", respectively. String values are also identified by "s".

    The table below summarizes formatting options for modifying numeric values.

    Example Output Explanation

    print("{:.7f}".format(0.9795))

    0.9795000

    The format specification .7 shows the output must have seven decimal places. The f specification is an identifier of floating-point formatting.

    print("{:.3f}".format(12))

    12.000

    The format specification .3 shows the output must have three decimal places. The f specification is an identifier of floating-point formatting.

    print("{:+.2f}".format(4))

    +4.00

    The format specification .2 shows the output must have two decimal places. The f specification is an identifier of floating-point formatting. The + sign before the precision specification adds a sign character to the output.

    print("{:0>5d}".format(5))

    00005

    The format specification 0>5 defines the width field as 5, and thus the output must have a minimum length of 5. And, if the number has fewer than five digits, the number must be padded with 0's from the left side. The d specification is an identifier of a decimal number formatting.

    print("{:.3s}".format("12.50"))

    12.

    The format specification .3 shows the output will have three characters. The s specification is an identifier of string formatting.

    Table 8.3: Numerical formatting options.
    Concepts in Practice \(\PageIndex{10}\): Numeric value formatting examples

    What is the output of print('{0:.3f}'.format(3.141592))?

    1. 3.141592
    2. 3.1
    3. 3.142
    Answer

    c. The .3 format specification shows that the output precision must be three decimal places.

    Concepts in Practice \(\PageIndex{11}\): Numeric value formatting examples

    What is the output of print('{:1>3d}'.format(3))?

    1. 113
    2. 311
    3. 3.000
    Answer

    a. The {:1>3d} specification outputs a 3-digit number in the output, and if the given argument does not have three digits, the number will be padded with 1's from the left side.

    Concepts in Practice \(\PageIndex{12}\): Numeric value formatting examples

    What is the output of print('{:+d}'.format(123))?

    1. 123
    2. +123
    3. :+123
    Answer

    b. {:+d} formats the decimal number by adding the positive sign.

    Try It: Formatting a list of numbers

    Given a list of numbers (floating-point or integer), print numbers with two decimal place precision and at least six characters.

        Input: [12.5, 2]
        Prints: 012.50
        
        002:00
    Interactive Code
    numbers = [10, 10.0, 1, 12.5]
    
     
    Answer

    numbers = [10, 10.0, 1, 12.5]
    for i in numbers:
    print("{:06.2f}".format(i))


    This page titled 8.4: String Formatting is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.