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


如图所示第10行代码,f{}格式化变量嵌套为什么不可以呢?
我有试过将最里面的f后面的双引号改成单引号竟然成功了!所以这是不是嵌套的正确方式?
最后一个问题:我以后可以直接使用中文进行提问嘛?
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?

谢谢您的回复,可能python中不能进行嵌套。
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.