2025 最新版 Python 的 format() 函數
在 Python 中,`format()` 函數是一個強大且靈活的工具,用於格式化字串。它讓我們能夠以更易讀的方式展示數據,並方便地將變數插入字串。隨著 Python 的演進,使用 `f-string`(格式化字串字面量)也成為了一種更簡潔的替代方案,但了解 `format()` 的使用仍然至關重要。
### format() 函數的基本語法
`format()` 函數的基本語法如下:
“`python
format(value[, format_spec])
“`
– **value**:要格式化的值。
– **format_spec**:指定格式的字串,這是可選的。
### 基本範例
以下是一個簡單的範例,展示如何使用 `format()` 函數:
“`python
name = ‘John’
print(‘Hello, {}’.format(name))
“`
輸出結果:
“`
Hello, John
“`
在這個範例中,我們將變數 **name** 插入到字串中,並使用 `format()` 函數進行格式化。
### 更複雜的範例
以下是一個更複雜的範例,展示如何使用 `format()` 函數來格式化多個變數:
“`python
name = ‘John’
age = 20
print(‘{0} is {1} years old’.format(name, age))
“`
輸出結果:
“`
John is 20 years old
“`
在這個範例中,我們將變數 **name** 和 **age** 插入到字串中,並使用 `format()` 函數進行格式化。
### 錯誤排除
在使用 `format()` 函數時,常見的錯誤包括:
– **索引錯誤**:如果在格式化字串中引用不存在的索引,會引發 `IndexError`。
– **格式錯誤**:使用不正確的格式規範可能會導致意外的輸出。
例如:
“`python
# 錯誤範例
print(‘{0} is {1} years old’.format(name))
“`
這將引發 `IndexError`,因為只提供了一個參數。
### 延伸應用
在 Python 3.6 及以後版本中,推薦使用 `f-string` 進行字串格式化。以下是 `f-string` 的範例:
“`python
name = ‘John’
age = 20
print(f'{name} is {age} years old’)
“`
這種方法簡潔且可讀性高,是當前最佳實踐。
### 小結
`format()` 函數是一個非常有用的工具,能夠讓字串格式化變得簡單明瞭。無論是基本的變數插入,還是更複雜的格式化需求,`format()` 函數都能有效應對。對於更高效的格式化方式,建議學習並使用 `f-string`。
如需深入了解 Python 的更多技巧和教學,請參考我們的 [Vocus Python 教學](https://vocus.cc) 或 [Miner Python 進階教學](https://miner.tw)。
### Q&A(常見問題解答)
**Q1: Python 的 `format()` 函數和 f-string 有什麼區別?**
A1: `format()` 函數是一種舊的格式化方式,而 f-string 是從 Python 3.6 開始引入的新語法,提供更簡潔的格式化方式,並且性能更佳。
**Q2: 如何使用 `format()` 函數進行數字格式化?**
A2: 可以在 `format_spec` 中指定數字格式,例如:`print(‘Price: ${:.2f}’.format(10.5))`,這將輸出 `Price: $10.50`。
**Q3: `format()` 函數可以用於格式化日期嗎?**
A3: 是的,`format()` 函數可以與 datetime 模組結合使用來格式化日期,例如:`print(‘Today is: {}’.format(datetime.datetime.now()))`。
—