String Formatting – Exercise Worksheet
Practice questions to strengthen your understanding of f-strings, .format(), and formatting specifiers.
1. Basic f-string Questions
-
Write an f-string that prints:
Name: Ravi, Age: 21 -
Given:
Print:name = "Asha" score = 87Asha scored 87 marks. -
Convert this to an f-string (don’t use
+):"Hello " + name + ", welcome!"
2. Number Formatting
- Format
3.14159to show exactly 2 decimal places. - Format
25000to include a comma (output:25,000). - Print
0.456as a percentage with 1 decimal place.
3. Alignment & Padding
- Center the text
"PYTHON"in a width of 20 characters. - Left-align the text
"Data"in a space of 10 characters. -
Pad the number
42so output becomes:00042
4. .format() Method
-
Use
.format()to print:My city is Mumbai -
Reorder:
What is the output?"{1} is before {0}".format("Beta", "Alpha")
5. Output Prediction
-
Predict output:
print(f"{5/2:.1f}") -
Predict output:
print("Value: {:>6}".format(42)) -
Predict output:
print(f"{'Hi':^10}")
6. Bonus Practice
- Create a formatted invoice line like:
Item: Pen Qty: 3 Price: ₹45.00 -
Format a report card line:
Riya | Maths: 92 | Science: 88 | Avg: 90.0% -
Build a multiline formatted message using f-string:
Hi Rahul, Your order (#12345) is packed. Amount: ₹599.00