DEV Community

Vladimir Ignatev
Vladimir Ignatev

Posted on • Updated on

Python quiz ๐Ÿค”: Can You Spot the Correct Python String Formatting?

๐Ÿ’ก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)
Enter fullscreen mode Exit fullscreen mode

Sample 2

name = "Alice"
age = 30
greeting = "Hello, {name}. You are {age} years old."
print(greeting)
Enter fullscreen mode Exit fullscreen mode

Share your thoughts and open up the explanation in the comments below! Let's see who gets it right! ๐ŸŒŸ๐Ÿ‘ฉโ€๐Ÿ’ป

or Go to Quiz 2/64

Top comments (2)

Collapse
 
vladignatyev profile image
Vladimir Ignatev

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.

Collapse
 
marisogo profile image
Marine

Love the concept!