TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Python f-strings are the best syntax sugar i never knew about

15 点作者 pyedpiper超过 7 年前
I've written `"text {foo}".format(foo=foo)` so many times I've almost convinced myself that it's not that verbose. Then i discovered fstrings introduced ins 3.6: ``` >>> f"text {fpp}" 'text foo' ``` >>> mind == blown True

6 条评论

tedmiston超过 7 年前
You can do cool nested calls with them too.<p><pre><code> &gt;&gt;&gt; class A: ... def __init__(self): ... self.foo = 5 ... def bar(self): ... return &#x27;cake&#x27; ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; f&#x27;{a.foo}&#x27; &#x27;5&#x27; &gt;&gt;&gt; f&#x27;{a.bar()}&#x27; &#x27;cake&#x27; &gt;&gt;&gt; x = {&#x27;b&#x27;: 1, &#x27;c&#x27;: 2} &gt;&gt;&gt; f&quot;{x[&#x27;b&#x27;]}&quot; &#x27;1&#x27;</code></pre>
评论 #16223096 未加载
评论 #16224960 未加载
in9超过 7 年前
it is very very true. F-strings are awesome. But there is one use case that I prefer .format(), and is when formatting a string using a dictionary. Being able to <i></i> is awesome:<p><pre><code> some_long_string_template.format(**some_dictionary_with_many_keys) </code></pre> For me that is such a nice and practical use case. But yes for not many local variables, f-string is the way to go.
评论 #16232906 未加载
kristoff_it超过 7 年前
Templated strings are great for when, as the name suggests, you want to create a string with some placeholders to be expanded at a later time.<p>When you just want to interpolate a string on the fly, Fstrings are absolutely the right thing to do most of the time.
评论 #16224952 未加载
jxub超过 7 年前
You could also do: &quot;text {}&quot;.format(foo) Works in Python 3.5 and earlier ones too.
dozzie超过 7 年前
Ah yes, the thing we had in shell, Perl, and Ruby since forever, and that was never a very good idea.
评论 #16224421 未加载
mailslot超过 7 年前
Thanks! I didn&#x27;t know I had literal string interpolation available until today!