0
0
Pythonprogramming~20 mins

Formatting using format() method in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Format Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of positional and keyword arguments in format()
What is the output of this code snippet?
Python
result = "{1} scored {score} points".format("Alice", "Bob", score=95)
print(result)
ABob scored 95 points
BAlice scored 95 points
C1 scored 95 points
DIndexError
Attempts:
2 left
💡 Hint
Remember that numbers inside curly braces refer to positional arguments by index.
Predict Output
intermediate
2:00remaining
Using format() with alignment and width
What will this code print?
Python
print("|{:<10}|{:^10}|{:>10}|".format('left', 'center', 'right'))
A|left |center | right|
B| left| center |right |
C|left|center|right|
D|left | center | right|
Attempts:
2 left
💡 Hint
Check the alignment symbols: < for left, ^ for center, > for right.
🧠 Conceptual
advanced
2:00remaining
Understanding nested replacement fields
What is the output of this code?
Python
data = {'name': 'John', 'age': 30}
print("{0[name]} is {0[age]} years old".format(data))
AJohn is 30 years old
B{0[name]} is {0[age]} years old
CTypeError
DKeyError
Attempts:
2 left
💡 Hint
The 0 refers to the first argument, which is a dictionary.
Predict Output
advanced
2:00remaining
Formatting floats with precision and padding
What does this code print?
Python
print("{num:0>8.3f}".format(num=12.34567))
A12.34600
B0012.346
C000012.3467
D12.34567
Attempts:
2 left
💡 Hint
0>8 means pad with zeros on the left to width 8, .3f means 3 decimal places.
Predict Output
expert
2:30remaining
Using format() with dynamic field names and expressions
What is the output of this code?
Python
person = {'first': 'Jane', 'last': 'Doe'}
index = 'first'
print("{0[{1}]} {0[last]}".format(person, index))
AKeyError
Bfirst Doe
CJane Doe
DIndexError
Attempts:
2 left
💡 Hint
The second argument is used as a key to access the dictionary in the first argument.