💡As I mentioned before, learning PEPs can help you learn Python. This post is about PEP-0498 - Literal String Interpolation.
So, follow me to learn 🐍 Python in 5-minute a day fun quizzes!
Quiz 1 out of 64
Which one of these code samples below is done right for string formatting in Python? Answer with 0 for the first sample or 1 for the second sample.
Sample 1
name = "Alice"
age = 30
greeting = f"Hello, {name}. You are {age} years old."
print(greeting)
Sample 2
name = "Alice"
age = 30
greeting = "Hello, {name}. You are {age} years old."
print(greeting)
Share your thoughts and open up the explanation in the comments below! Let's see who gets it right! 🌟👩💻
Top comments (2)
Explanation
The first code sample is the correct implementation of string formatting in Python according to PEP 498. This PEP introduced a simpler way to format strings known as Literal String Interpolation, or more commonly, "f-strings". By prefixing the string with f, variables can be directly embedded in the string using curly braces. This approach is both readable and efficient.
The second code sample, however, is incorrect for the intended use. It's a regular string with placeholders {name} and {age}, but without the f prefix or any formatting method applied. This will result in the string Hello, {name}. You are {age} years old. being printed literally, without substituting the variables name and age.
Love the concept!