0

Could someone please break down why "{dic['string_key']}".format(dic=dic) considers the single quotations to be part of the string-key and does a lookup under dic["'string_key'"] ?

a) and b) show the correct way, however I am missing the reason.

a = "{dic[string_key]}"
print(a.format(dic=dic))

b = f"{dic['string_key']}"
print(b)
1

2 Answers 2

2

format and f-strings use braces differently.

With str.format, the contents of the braces are part of a mini-language used by format to substitute its arguments into the format string.

In an f-string, it's an arbitrary Python expression to evaluate.

Sign up to request clarification or add additional context in comments.

Comments

1

In this case:

a = "{dic[string_key]}"
print(a.format(dic=dic))

... the string is formatted when .format() is called and that function uses a formatting language that is documented here https://docs.python.org/3/library/string.html#formatstrings.

But in this case:

b = f"{dic['string_key']}"
print(b)

... the string is formatted when the assignment to b is executed, by Python itself. The expression inside the f-string follows normal Python syntax, with the exception that you cannot reuse the quotes used to enclose the f-string.

As a result, you need to specify the quotes around the dictionary key as you would normally, while the mini-language for .format() expects you to omit them.

Also note that this makes a lot of sense: b = f"{dic[string_key]}" should use the value of the variable string_key to index the dictionary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.