在 Python 中,字串格式化是一項非常重要的技能,特別是當你需要清楚且有效地呈現資料時。2025 年的最佳實踐是使用 f-string 語法,但在本文中,我們將深入探討傳統的 `format()` 方法,了解如何使用它來提升程式的可讀性與維護性。
### Python 字串 format() 語法
`format()` 方法允許你在字串中插入變數,而不需要直接使用字串連接,這樣可以讓程式碼更整潔。以下是幾個常見的用法:
#### 基本使用
你可以透過 `format()` 方法將變數插入字串中,例如:
“`python
name = ‘John’
print(‘Hello, {}’.format(name))
“`
這段程式碼的輸出為:
“`
Hello, John
“`
#### 多個變數
你也可以同時使用多個變數:
“`python
name = ‘John’
age = 20
print(‘{} is {} years old’.format(name, age))
“`
這將輸出:
“`
John is 20 years old
“`
#### 使用索引
使用索引可以讓你控制變數的順序:
“`python
name = ‘John’
age = 20
print(‘{1} is {0} years old’.format(age, name))
“`
輸出結果仍然是:
“`
John is 20 years old
“`
#### 使用字典
若有一個字典,你可以使用 `**` 操作符自動解包字典來插入變數:
“`python
person = {‘name’: ‘John’, ‘age’: 20}
print(‘{name} is {age} years old’.format(**person))
“`
輸出將是:
“`
John is 20 years old
“`
### 錯誤排除
在使用 `format()` 時,常見的錯誤包括:
– **位置錯誤**:若忘記提供對應的變數,會導致 `IndexError`。
– **鍵錯誤**:使用字典時,若鍵名拼寫錯誤,會導致 `KeyError`。
### 延伸應用
隨著 Python 的發展,從 Python 3.6 開始,推薦使用 **f-string** 進行字串格式化,這種方法更加簡潔且效率更高。例如:
“`python
name = ‘John’
age = 20
print(f'{name} is {age} years old’)
“`
這樣的寫法不僅可讀性強,性能也更佳。
### 結論
學會使用 Python 的字串格式化功能能夠大幅提升程式的可讀性與維護性。希望這篇文章能幫助你更好地掌握 `format()` 方法及其應用。
你可以查看更多 Python 教學文章,例如 [Python 格式化字串的最佳實踐](https://vocus.cc) 以深入理解字串處理。
### Q&A(常見問題解答)
**Q1: Python 中的字串格式化有幾種方法?**
A1: 主要有三種:`%` 格式化、`str.format()` 方法,和 Python 3.6 引入的 f-string。
**Q2: 為什麼選擇使用 f-string?**
A2: f-string 更加簡潔,且在性能上優於其他格式化方法,特別是在需要多次格式化的情況下。
**Q3: 如何處理字典中的變數格式化?**
A3: 使用 `**` 操作符可將字典解包,直接在字串中引用鍵名。
—