📌 Pinned: Treat all vulnerable road users as if they were your closest family. Maintain a safe following distance from the vehicle in front (at least 2 seconds).

(那些過時的) Python 字串格式化以及 f-string 字串格式化

In

Tags:



by

在 Python 裡頭,目前的最新版本 (3.6.2) 中總共有 3 種不同的方式來達成字串格式化 (String format)。分別是 %-formatting、str.format 以及 f-string。本文將會逐一介紹這些 Python 的字串格式化方式。

01. %-formatting

偉大的 C 語言字串格式化深入我們的生活,Python 自然也不意外的會有這個功能。

從今天開始,忘了它。

02. str.format

PEP 3101 帶來了 str.format(),讓我們可以用 .format 的方式來格式化字串:

各種技巧請參考:Format Specification Mini-Language

從今天開始,忘了它。

03. f-string

PEP 498 帶來了 f-string,它的學名叫作 “Literal String Interpolation”。用法如下:

還可以這樣:

從今天開始使用 f-string!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.