0
0
Pythonprogramming~20 mins

String formatting using f-strings in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
F-string Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of f-string with expressions
What is the output of this Python code?
Python
name = "Alice"
age = 30
print(f"{name} will be {age + 5} years old in 5 years.")
AAlice will be 35 years old in 5 years.
BAlice will be age + 5 years old in 5 years.
CAlice will be 30 + 5 years old in 5 years.
DSyntaxError
Attempts:
2 left
💡 Hint
Remember that expressions inside curly braces in f-strings are evaluated.
Predict Output
intermediate
2:00remaining
Formatting numbers with f-strings
What is the output of this code?
Python
value = 3.14159
print(f"Value rounded to 2 decimals: {value:.2f}")
AValue rounded to 2 decimals: 3.14159
BValue rounded to 2 decimals: 3.14
CValue rounded to 2 decimals: 3.1
DValue rounded to 2 decimals: 3.15
Attempts:
2 left
💡 Hint
The format specifier .2f rounds the float to 2 decimal places.
Predict Output
advanced
2:00remaining
Using f-string with dictionary values
What will this code print?
Python
person = {"name": "Bob", "age": 25}
print(f"{person['name']} is {person['age']} years old.")
ABob is 25 years old.
B{person['name']} is {person['age']} years old.
CSyntaxError
DBob is person['age'] years old.
Attempts:
2 left
💡 Hint
You can use dictionary keys inside the curly braces in f-strings.
Predict Output
advanced
2:00remaining
Nested f-string expressions
What is the output of this code?
Python
x = 4
print(f"Square of {x} is {x**2} and cube is {x**3}.")
ASquare of 4 is 8 and cube is 12.
BSquare of x is x**2 and cube is x**3.
CSyntaxError
DSquare of 4 is 16 and cube is 64.
Attempts:
2 left
💡 Hint
Expressions inside curly braces are evaluated before printing.
Predict Output
expert
2:00remaining
Using f-string with alignment and padding
What is the output of this code?
Python
for i in range(1,4):
    print(f"Number: {i:>3}")
A
Number:1
Number:2
Number:3
B
Number: 1
Number: 2
Number: 3
C
Number:  1
Number:  2
Number:  3
DSyntaxError
Attempts:
2 left
💡 Hint
The >3 means right-align the number in a space of width 3.