f-string

Nested f-strings

喜欢而已 提交于 2019-11-26 16:38:52
问题 Thanks to David Beazley's tweet, I've recently found out that the new Python 3.6 f-strings can also be nested: >>> price = 478.23 >>> f"{f'${price:0.2f}':*>20s}" '*************$478.23' Or: >>> x = 42 >>> f'''-{f"""*{f"+{f'.{x}.'}+"}*"""}-''' '-*+.42.+*-' While I am surprised that this is possible, I am missing on how practical is that, when would nesting f-strings be useful? What use cases can this cover? Note: The PEP itself does not mention nesting f-strings, but there is a specific test

String with 'f' prefix in python-3.6

烂漫一生 提交于 2019-11-26 16:13:34
I'm trying out Python 3.6. Going through new code, I stumbled upon this new syntax: f"My formatting string!" It seems we can do things like this: >>> name = "George" >>> print(f"My cool string is called {name}.") My cool string is called George. Can anyone shed some light on the inner workings of this? In particular what is the scope of the variables that an f-prefixed string can take? Kwong Leong See PEP 498 Literal String Interpolation : The expressions that are extracted from the string are evaluated in the context where the f-string appeared. This means the expression has full access to

f-strings in Python 3.6

会有一股神秘感。 提交于 2019-11-26 12:26:56
问题 I really like to delve into code style and it\'s interesting to know whether from now on in all cases it would be better to use the new style. I\'m using a lot the .format() in my Python 3.5 projects, and I\'m afraid that it will be deprecated during the next Python versions because of this new kind of string literals. >>> name = \"Test\" >>> f\"My app name is {name}.\" \'My app name is Test.\' Does the formatted string feature come to fully replace the old format() ? I understand that it

How to postpone/defer the evaluation of f-strings?

ⅰ亾dé卋堺 提交于 2019-11-26 08:56:39
问题 I am using template strings to generate some files and I love the conciseness of the new f-strings for this purpose, for reducing my previous template code from something like this: template_a = \"The current name is {name}\" names = [\"foo\", \"bar\"] for name in names: print (template_a.format(**locals())) Now I can do this, directly replacing variables: names = [\"foo\", \"bar\"] for name in names: print (f\"The current name is {name}\") However, sometimes it makes sense to have the

String with 'f' prefix in python-3.6

。_饼干妹妹 提交于 2019-11-26 04:45:35
问题 I\'m trying out Python 3.6. Going through new code, I stumbled upon this new syntax: f\"My formatting string!\" It seems we can do things like this: >>> name = \"George\" >>> print(f\"My cool string is called {name}.\") My cool string is called George. Can anyone shed some light on the inner workings of this? In particular what is the scope of the variables that an f-prefixed string can take? 回答1: See PEP 498 Literal String Interpolation: The expressions that are extracted from the string are