2025 最新版 Python 字串格式化教學:深入了解 format() 函數的強大功能

在 Python 中,format() 函數是一個強大的工具,能夠幫助我們將字串格式化為所需的樣式。它的功能與 C 語言中的 sprintf() 函數相似,適合用於創建動態字串。在這篇文章中,我們將探討 format() 函數的基本用法以及一些進階技巧,並提供實作範例、錯誤排除方法以及延伸應用。

目錄

format() 的基本使用方式

基本的 format() 使用方式是將需要格式化的字串放在大括號中,然後在函數中傳入對應的參數。以下是範例:


name = "John"
age = 20

print("My name is {}, and I am {} years old.".format(name, age))

執行上面的程式,會得到以下的輸出:


My name is John, and I am 20 years old.

使用位置參數

我們可以使用位置參數來指定字串格式化的順序,如下範例:


name = "John"
age = 20

print("My name is {0}, and I am {1} years old.".format(name, age))

這段程式碼的輸出將會是:


My name is John, and I am 20 years old.

使用關鍵字參數

除了位置參數,format() 也支持關鍵字參數,這樣可以使代碼更加清晰易懂:


name = "John"
age = 20

print("My name is {name}, and I am {age} years old.".format(name=name, age=age))

執行後的輸出將會是:


My name is John, and I am 20 years old.

使用 *args 和 **kwargs

我們也可以使用 *args**kwargs 對格式化進行更靈活的操作,以下是範例:


name = "John"
age = 20

args = (name, age)
kwargs = {'name': name, 'age': age}

print("My name is {0[0]}, and I am {0[1]} years old.".format(args))
print("My name is {name}, and I am {age} years old.".format(**kwargs))

這段程式碼的輸出將會是:


My name is John, and I am 20 years old.
My name is John, and I am 20 years old.

錯誤排除

在使用 format() 函數時,如果遇到 IndexErrorKeyError,通常是因為提供的參數與格式化字符串不匹配。確保所有位置和關鍵字參數都正確對應,這樣可以避免這些錯誤。

延伸應用

除了基本的字串格式化,format() 還可以用於格式化數字、日期等。舉例來說:


import datetime

today = datetime.datetime.now()
print("Today's date is: {}".format(today.strftime("%Y-%m-%d")))

這段程式碼會輸出當前日期,格式為 YYYY-MM-DD。

總結

Python 的 format() 函數是一個靈活且強大的字串格式化工具,支持多種參數傳遞方式。掌握這些技巧可以讓你的代碼更加整潔和易於維護。

Q&A(常見問題解答)

1. format() 函數和 f-strings 有什麼區別?

f-strings 是 Python 3.6 及以後版本引入的一種格式化字符串的方法,語法更簡單易用。使用 f-strings,可以直接在字符串前加上字母 “f”,並在大括號中放入變量名。

2. format() 函數是否支持多種數據類型的格式化?

是的,format() 函數支持多種數據類型的格式化,包括整數、浮點數、字串等,並且可以進行各種格式設定,例如小數點位數、字串填充等。

3. 如何在 format() 中使用自定義格式?

可以通過在大括號內指定格式來實現,例如對浮點數的格式化,可以這樣寫:"The value is {:.2f}".format(value),這樣可以保留兩位小數。

發佈留言