Question -> Python Formatted Strings

Greetings:

In the 6 hour Python tutorial video (LINK: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=2392), Mosh said the following from 40:01 to 40:10:

<<With these curly braces, we’re defining placeholders or holes in our string, and when we run our program, these holes will be filled with the values of our variables.>>

What does he mean by a placeholder or hole? Does it refer to a specific location within the string where a value can be inserted or substituted (ChatGPT’S answer that is uncertain because ChatGPT can generate inaccurate information)? Or does it mean something else in this context?

If you have a simple combination of variables you want to print out, you could easily do it by saying:

print a + b

But let’s say you want to build a more complex string and possible include numerical formatting, such as currency. You may need to apply special formatting to get the right number of decimal places, etc. That’s what format() is for. Although it also works in simple scenarios like this:

a = “abc”
b = “def”

print(“My String: {}{}”.format(a, b));

The curly braces are placeholders. Since you see {} appears twice, that means the format command is looking for two variables to put in those locations of your new string.

In that case, it prints the text "My String: ", then it uses the variables a and b to fill in where the curly braces are. The number or arguments must match the number of {}.

You’ll learn more advanced usages for this later on. But one way to learn is to experiment with it.

Try something like this:

a = 1
b = 2
print(“add {} + {} = {}”.format(a, b, a+b);

Hope that helps.

Jerry

1 Like