String Formatting

F-strings (Preferred)

  1. # basic f-string
  2. name = "Alice"
  3. age = 25
  4. f"Hello, {name}!"
  5. #ans: "Hello, Alice!"
  6. f"{name} is {age} years old"
  7. #ans: "Alice is 25 years old"

F-strings with Expressions

  1. # expressions in f-strings
  2. x = 10
  3. y = 20
  4. f"{x} + {y} = {x + y}"
  5. #ans: "10 + 20 = 30"

F-strings Formatting

  1. # format specifiers
  2. pi = 3.14159
  3. f"{pi:.2f}"
  4. #ans: "3.14"
  5. num = 42
  6. f"{num:05d}"
  7. #ans: "00042"

Format Method

  1. # str.format()
  2. "Hello, {}!".format("World")
  3. #ans: "Hello, World!"
  4. "{} + {} = {}".format(2, 3, 5)
  5. #ans: "2 + 3 = 5"

Format with Names

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

Old Style (%)

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

Exercises - Part 1

  1. # basic f-string?
  2. x = 5
  3. f"Value: {x}"
  4. #ans: "Value: 5"

Exercises - Part 2

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

Exercises - Part 3

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

Exercises - Part 4

  1. # padding with zeros?
  2. num = 7
  3. f"{num:03d}"
  4. #ans: "007"

Exercises - Part 5

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

Exercises - Part 6

  1. # format with index?
  2. "{1} {0}".format("World", "Hello")
  3. #ans: "Hello World"

Exercises - Part 7

  1. # % with tuple?
  2. "Name: %s, Age: %d" % ("Alice", 25)
  3. #ans: "Name: Alice, Age: 25"

Exercises - Part 8

  1. # f-string debugging (3.8+)?
  2. x = 42
  3. f"{x=}"
  4. #ans: "x=42"

Exercises - Part 9

  1. # alignment?
  2. name = "Al"
  3. f"{name:>10}"
  4. #ans: " Al"
  5. f"{name:<10}"
  6. #ans: "Al "

Exercises - Part 10

  1. # multiline f-string?
  2. name = "Alice"
  3. age = 25
  4. f"""Name: {name}
  5. Age: {age}"""
  6. #ans: "Name: Alice\nAge: 25"

Google tag (gtag.js)