0
0
Pythonprogramming~5 mins

String formatting using f-strings in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an f-string in Python?
An f-string is a way to embed expressions inside string literals, using curly braces {} and prefixing the string with the letter 'f'. It makes string formatting easier and more readable.
Click to reveal answer
beginner
How do you include a variable named name inside an f-string?
You write the string with an f before the quotes and put the variable inside curly braces like this: f"Hello, {name}!".
Click to reveal answer
intermediate
How can you format a floating-point number to show only 2 decimal places using f-strings?
Use a format specifier inside the braces like this: f"{value:.2f}". This rounds the number to 2 decimal places.
Click to reveal answer
intermediate
Can you use expressions inside f-strings? Give an example.
Yes! You can put any valid Python expression inside the braces. For example: f"5 + 3 = {5 + 3}" will output 5 + 3 = 8.
Click to reveal answer
advanced
How do you include a literal curly brace character in an f-string?
To include a curly brace, double it: use {{ for { and }} for }. For example: f"{{Hello}}" outputs {Hello}.
Click to reveal answer
What prefix do you add before a string to create an f-string in Python?
Af
Bs
Cr
Db
How would you format the number 3.14159 to show only 2 decimal places using an f-string?
Af"{3.14159:2d}"
Bf"{3.14159:.2d}"
Cf"{3.14159:.2f}"
Df"{3.14159:2f}"
What will this code print? <br> name = 'Sam'<br>print(f"Hello, {name}!")
AHello, {name}!
BHello, Sam!
CHello, name!
DError
How do you include a literal curly brace '{' in an f-string?
AYou cannot include literal braces in f-strings
BUse a backslash before it: \{
CPut it inside quotes: '{'
DDouble the brace: {{
Can you put calculations inside the curly braces of an f-string?
AYes, any valid Python expression can be used
BOnly string operations are allowed
COnly simple math operations are allowed
DNo, only variables are allowed
Explain how to use f-strings to include variables and expressions inside strings.
Think about how you write the string and where you put the variable names.
You got /4 concepts.
    Describe how to format numbers with specific decimal places using f-strings.
    Look inside the braces for a colon and formatting code.
    You got /4 concepts.