Skip to main content
Engineering LibreTexts

3.2: Formatted Strings

  • Page ID
    117534
  • \( \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

    • Use f-strings to simplify output with multiple values.
    • Format numbers with leading zeros and fixed precision.

    F-strings

    A formatted string literal (or f-string) is a string literal that is prefixed with "f" or "F". A replacement field is an expression in curly braces ({}) inside an f-string. Ex: The string f"Good morning, {first} {last}!" has two replacement fields: one for a first name, and one for a last name. F-strings provide a convenient way to combine multiple values into one string.

    Checkpoint: Printing an f-string
    Concepts in Practice \(\PageIndex{1}\): Basic f-strings

    What is the output of the following code?

    animal = "dog"
    says = "bark"
    print(f"My {animal} says {says} {says} {says}")
    
    1. My dog bark bark bark bark
    2. My dog says bark bark bark
    3. Error
    Answer

    b. The same variable, says, is used in three replacement fields.

    Concepts in Practice \(\PageIndex{2}\): Basic f-strings

    What is the output of the following code?

    temp = "hot"
    food = "potato"
    print("{temp} {food}")
    
    1. {temp} {food}
    2. hot potato
    3. Error
    Answer

    a. The string is not an f-string, so the brace characters (around temp and food) are printed literally.

    Concepts in Practice \(\PageIndex{3}\): Basic f-strings

    How can the following code be rewritten using an f-string?

    print(x, "+", y, "=", x + y)
    
    1. print(f"x + y = {x+y}")
    2. print(f"{x + y} = {x + y}")
    3. print(f"{x} + {y} = {x+y}")
    Answer

    c. Using an f-string allows the entire output to be specified without commas and extra quote marks.

    Formatting numbers

    Programs often need to display numbers in a specific format. Ex: When displaying the time, minutes are formatted as two-digit integers. If the hour is 9 and the minute is 5, then the time is "9:05" (not "9:5").

    In an f-string, a replacement field may include a format specifier introduced by a colon. A format specifier defines how a value should be formatted for display. Ex: In the string f"{hour}:{minute:02d}", the format specifier for minute is 02d.

    Table 3.3 Example format specifiers. The table shows common ways that numbers can be formatted. Many more formatting options are available and described in Python's Format Specification Mini-Language.
    Format Description Example Result

    d

    Decimal integer (default integer format).

    f"{12345678:d}"

    '12345678'

    ,d

    Decimal integer, with comma separators.

    f"{12345678:,d}"

    '12,345,678'

    10d

    Decimal integer, at least 10 characters wide.

    f"{12345678:10d}"

    ' 12345678'

    010d

    Decimal integer, at least 10 characters wide, with leading zeros.

    f"{12345678:010d}"

    '0012345678'

    f

    Fixed-point (default is 6 decimal places).

    f"{math.pi:f}"

    '3.141593'

    .4f

    Fixed-point, rounded to 4 decimal places.

    f"{math.pi:.4f}"

    '3.1416'

    8.4f

    Fixed-point, rounded to 4 decimal places, at least 8 characters wide.

    f"{math.pi:8.4f}"

    ' 3.1416'

    08.4f

    Fixed-point, rounded to 4 decimal places, at least 8 characters wide, with leading zeros.

    f"{math.pi:08.4f}"

    '003.1416'

    Concepts in Practice \(\PageIndex{4}\): Formatting numbers

    What f-string formats a date as MM/DD/YYYY?

    1. f"{month:02d}/{day:02d}/{year}"
    2. f"{month:2d}/{day:2d}/{year}"
    3. f"{month}/{day}/{year}"
    Answer

    a. The format specifier 02d appends a 0 to the front of the integer when the integer is only one digit.

    Concepts in Practice \(\PageIndex{5}\): Formatting numbers

    What statement displays the variable money rounded to two decimal places?

    1. print(f"{money:2d}")
    2. print(f"{money:2f}")
    3. print(f"{money:.2f}")
    Answer

    c. The format specifier ".2f" (with a period) means fixed-point, rounded to two decimal places.

    Concepts in Practice \(\PageIndex{6}\): Formatting numbers

    What format specifier displays a floating-point number with comma separators and rounded to two decimal places?

    1. .2,f
    2. ,.2f
    3. ,d.2f
    Answer

    b. This format specifier is useful for displaying large amounts of money.

    Try It: Mad lib (f-string)

    A mad lib is a funny story that uses words provided by a user. The following mad lib is based on four words (user input in bold):

        Enter a name: Buster
        Enter a noun: dog
        Enter an adjective: super
        Verb ending in -ing: swimming
        
        Buster, the super dog, likes to go swimming.

    Most of the code for this mad lib is already written. Complete the code below by writing the f-string.

    Interactive Code
    name = input("Enter a name: ")
    noun = input("Enter a noun: ")
    adjective = input("Enter an adjective: ")
    verb_ing = input("Verb ending in -ing: ")
    
    print()
    print(f"")  # TODO: edit this line only
    
     
    Input

    Buster
    dog
    super
    swimming

    Answer

    name = input("Enter a name: ")
    noun = input("Enter a noun: ")
    adjective = input("Enter an adjective: ")
    verb_ing = input("Verb ending in -ing: ")

    print()
    print(f"{name}, the {adjective} {noun}, likes to go {verb_ing}.")

    Try It: Wage calculator

    You just landed a part-time job and would like to calculate how much money you will earn. Write a program that inputs the time you start working, the time you stop working, and your hourly pay rate (example input in bold):

        Starting hour: 9
        Starting minute: 30
        Stopping hour: 11
        Stopping minute: 0
        Hourly rate: 15

    Based on the user input, your program should calculate and display the following results:

        Worked 9:30 to 11:00
        Total hours: 1.5
        Payment: $22.50

    For this exercise, you need to write code that (1) calculates the total payment and (2) formats the three output lines. Use f-strings and format specifiers to display two-digit minutes, one decimal place for hours, and two decimal places for payment. The input code has been provided as a starting point.

    Assume the use of a 24-hour clock. Ex: 16:15 is used instead of 4:15pm.

    Interactive Code
    start_hour = int(input("Starting hour: "))
    start_min = int(input("Starting minute: "))
    stop_hour = int(input("Stopping hour: "))
    stop_min = int(input("Stopping minute: "))
    rate = float(input("Hourly rate: "))
    print()
    
     
    Input

    9
    30
    11
    0
    15

    Answer

    start_hour = int(input("Starting hour: "))
    start_min = int(input("Starting minute: "))
    stop_hour = int(input("Stopping hour: "))
    stop_min = int(input("Stopping minute: "))
    rate = float(input("Hourly rate: "))
    print()

    start = start_hour*60 + start_min
    stop = stop_hour*60 + stop_min
    hours = (stop - start) / 60
    payment = hours * rate

    print(f"Worked {start_hour}:{start_min:02d} to {stop_hour}:{stop_min:02d}")
    print(f"Total hours: {hours:.1f}")
    print(f"Payment: ${payment:.2f}")


    This page titled 3.2: Formatted Strings 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.