Python · strings

String Formatting

Put values into text: f-strings, str.format() and the old % style.

f-strings (preferred)


          # basic f-string
          name = "Alice"
          age = 25
          f"Hello, {name}!"
          # ans: "Hello, Alice!"
          f"{name} is {age} years old"
          # ans: "Alice is 25 years old"
        
f"{name} is {age} years old"
an f before the quote turns {…} into fields
f"{'Alice'} is {25} years old"
each field is evaluated
"Alice is 25 years old"
and its text is dropped into place

f-strings with expressions


          # expressions in f-strings
          x = 10
          y = 20
          f"{x} + {y} = {x + y}"
          # ans: "10 + 20 = 30"
        
f"{x} + {y} = {x + y}"
any expression can go in the braces
f"{10} + {20} = {10 + 20}"
names are looked up
"10 + 20 = 30"
the + inside braces is arithmetic; outside it is just text

f-string format specifiers


          # format specifiers
          pi = 3.14159
          f"{pi:.2f}"
          # ans: "3.14"
          num = 42
          f"{num:05d}"
          # ans: "00042"
        

After the colon: .2f = float with 2 decimals; 05d = integer, width 5, zero-filled.

The format method


          # str.format()
          "Hello, {}!".format("World")
          # ans: "Hello, World!"
          "{} + {} = {}".format(2, 3, 5)
          # ans: "2 + 3 = 5"
        
"{} + {} = {}".format(2, 3, 5)
empty braces are filled in order...
"2 + {} = {}".format(2, 3, 5)
...first, second...
"2 + 3 = {}".format(2, 3, 5)
...third
"2 + 3 = 5"
done

Format with names


        # named placeholders
        "{name} is {age}".format(name="Alice", age=25)
        # ans: "Alice is 25"
      

Old style (%)


        # % formatting
        "Hello, %s!" % "World"
        # ans: "Hello, World!"
        "%d + %d = %d" % (2, 3, 5)
        # ans: "2 + 3 = 5"
      

%s = string, %d = integer. You will see this in older code.

Exercises

Predict the resulting string, then press → to check.

Exercise 1


        # basic f-string?
        x = 5
        f"Value: {x}"
        # ans: "Value: 5"
      

Exercise 2


        # f-string expression?
        x = 3
        f"{x} squared is {x**2}"
        # ans: "3 squared is 9"
      

Exercise 3


          # formatting decimals?
          pi = 3.14159
          f"{pi:.2f}"
          # ans: "3.14"
          f"{pi:.4f}"
          # ans: "3.1416"
        

Exercise 4


          # padding with zeros?
          num = 7
          f"{num:03d}"
          # ans: "007"
        

Exercise 5


        # format() method?
        "{}{}{}".format(1, 2, 3)
        # ans: "123"
      

Exercise 6


          # format with an index?
          "{1} {0}".format("World", "Hello")
          # ans: "Hello World"
        
"{1} {0}".format("World", "Hello")
arguments are numbered from 0
"{1} {0}".format(0:"World", 1:"Hello")
so {1} is "Hello" and {0} is "World"

Exercise 7


        # % with a tuple?
        "Name: %s, Age: %d" % ("Alice", 25)
        # ans: "Name: Alice, Age: 25"
      

Exercise 8


        # f-string debugging (3.8+)?
        x = 42
        f"{x=}"
        # ans: "x=42"
      

Exercise 9


          # alignment?
          name = "Al"
          f"{name:>10}"
          # ans: "        Al"
          f"{name:<10}"
          # ans: "Al        "
        

Both are 10 characters wide; the arrow points the way the text is pushed.

Exercise 10


        # multiline f-string?
        name = "Alice"
        age = 25
        f"""Name: {name}
        Age: {age}"""
        # ans: "Name: Alice\nAge: 25"
      

Remember

f-strings

f"{expr}": any expression, evaluated where the string is written.

Format specs

:.2f decimals, :05d zero padding, :>10 / :<10 alignment.

format()

{} fills in order, {1} by index, {name} by keyword.

%

The oldest style: %s, %d.