Python 的 format() 函數

Python 的 `format()` 函數是一個極其強大的工具,能夠讓開發者以簡單的方式格式化字串,並將字串中的特定部分替換為所需內容。在這篇文章中,我們將深入探討 `format()` 函數的基本用法及其進階應用,並提供實作範例,確保您能夠在實際開發中有效運用。

format() 函數的基本用法

`format()` 函數的基本用法是將字串中的特定部分替換為指定的內容。例如:

name = "John"
print("Hello, {name}!".format(name=name))

上面的程式碼會輸出:

Hello, John!

這裡,我們使用了大括號 `{}` 來指定要替換的部分,並在 `format()` 函數中傳入對應的變數。

格式化數字

`format()` 函數也可以用來格式化數字。例如,您可以控制數字的小數位數:

num = 123.456789
print("The number is {num:.2f}".format(num=num))

上面的程式碼會輸出:

The number is 123.46

這裡,`: .2f` 表示將數字格式化為浮點數,並保留兩位小數。

格式化日期

除了字串和數字,`format()` 函數還可以用來格式化日期:

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

上面的程式碼會輸出當前日期,例如:

Today is 2025-06-01

這裡,`%Y-%m-%d` 用於指定日期的顯示格式。

格式化字典

您還可以使用 `format()` 函數格式化字典中的值:

person = {'name': 'John', 'age': 20}
print("{person[name]} is {person[age]} years old".format(person=person))

這樣會輸出:

John is 20 years old

格式化列表

`format()` 函數同樣支持列表格式化:

numbers = [1, 2, 3]
print("The numbers are {numbers[0]}, {numbers[1]}, and {numbers[2]}".format(numbers=numbers))

該程式碼的輸出為:

The numbers are 1, 2, and 3

總結

`format()` 函數是一個非常靈活的工具,可以用來格式化各種不同類型的數據。從字串到數字、日期、字典和列表,`format()` 函數幫助我們保持程式碼的簡潔與可讀性。

若想進一步學習 Python 的其他功能,建議參考 [這篇教學](https://vocus.cc) 以擴展您的知識。

Q&A(常見問題解答)

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

`format()` 函數是較早的字串格式化方法,而 f-string(格式化字串字面量)是 Python 3.6 及以後版本引入的語法,提供了更直觀的方式來格式化字串。

2. 如何在 format() 中使用多個變數?

您可以在字串中使用多個大括號並在 `format()` 函數中傳入多個變數,如:

print("Hello, {name}. You are {age} years old.".format(name="John", age=30))

3. format() 函數的性能如何?

在需要格式化大量字串時,`format()` 函數的性能可能不如 f-string,但在一般情況下,它的性能是可以接受的。

Categorized in:

Tagged in: