Ex5 更多的变量和打印More variables and printing

As shown in the 10th line of code, why can’t f{} format variable nesting?
I have tried to change the double quotation mark after the innermost f to a single quotation mark and it succeeded! So is this the correct way of nesting?
One last question: Can I directly ask questions in Chinese in the future?
Hope to reply, thank you!

Yes, think about it: What marks the end of a string (or f-string)?

I don’t think there are many people here who understand Chinese…

Hmmm, I hadn’t thought of this so I went to try it, but it looks like that’s not allowed:

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(f"This is a {f"Thing"}")
  File "<stdin>", line 1
    print(f"This is a {f"Thing"}")
SyntaxError: invalid syntax

You actually can’t put an f-string inside an f-string. There ya go. Oh well.

I think you can! You just have to use the other type of quotes, otherwise the scanner thinks the outer string ends where the inner begins. I guess it “munches” the whole f-string before it considers the embedded expressions?

Thank you for your reply, it may not be nested in python.

Thing = “test”
print(f"This is a {f’Thing’}")

PS C:\Users\zhuli\lpthw> & C:/Users/zhuli/AppData/Local/Programs/Python/Python38-32/python.exe c:/Users/zhuli/lpthw/test.py
This is a Thing

The variable becomes a string…

OK,I know,thank you very much!And there may not be too many people who can speak Chinese.

Well, your inner f-string doesn’t contain any expressions. It’s just a string. Try this:

>>> thing = "test"
>>> print(f"This is a {f'{thing}'}.")
This is a test.

Oh, thanks! It turns out I am missing one {}.

Haha! Wicked. I hadn’t thought of that simple fix.

A free service run by Zed A. Shaw for learncodethehardway.org.