String Formatting – Exercise Worksheet

Practice questions to strengthen your understanding of f-strings, .format(), and formatting specifiers.


1. Basic f-string Questions

  1. Write an f-string that prints:
    Name: Ravi, Age: 21
  2. Given:
    name = "Asha"
    score = 87
    Print:
    Asha scored 87 marks.
  3. Convert this to an f-string (don’t use +):
    "Hello " + name + ", welcome!"

2. Number Formatting

  1. Format 3.14159 to show exactly 2 decimal places.
  2. Format 25000 to include a comma (output: 25,000).
  3. Print 0.456 as a percentage with 1 decimal place.

3. Alignment & Padding

  1. Center the text "PYTHON" in a width of 20 characters.
  2. Left-align the text "Data" in a space of 10 characters.
  3. Pad the number 42 so output becomes:
    00042

4. .format() Method

  1. Use .format() to print:
    My city is Mumbai
  2. Reorder:
    "{1} is before {0}".format("Beta", "Alpha")
    What is the output?

5. Output Prediction

  1. Predict output:
    print(f"{5/2:.1f}")
  2. Predict output:
    print("Value: {:>6}".format(42))
  3. Predict output:
    print(f"{'Hi':^10}")

6. Bonus Practice

  1. Create a formatted invoice line like:
    Item: Pen      Qty: 3     Price: ₹45.00
  2. Format a report card line:
    Riya | Maths: 92 | Science: 88 | Avg: 90.0%
  3. Build a multiline formatted message using f-string:
    
    Hi Rahul, 
    Your order (#12345) is packed.
    Amount: ₹599.00
            

← Back to Topics