# Python 字符串格式化
> 原文: [https://thepythonguru.com/python-string-formatting](https://thepythonguru.com/python-string-formatting)
* * *
于 2020 年 1 月 7 日更新
* * *
`format()`方法允許您以任何所需的方式格式化字符串。
**語法**: `template.format(p1, p1, .... , k1=v1, k2=v2)`
模板是一個包含格式代碼的字符串,`format()`方法使用它的參數替換每個格式代碼的值。 例如:
```py
>>> 'Sam has {0} red balls and {1} yellow balls'.format(12, 31)
```
`{0}`和`{1}`是格式代碼。 格式代碼`{0}`替換為`format()`的第一個參數,即`12`,而`{1}`替換為`format()`的第二個參數,即`31`。
**預期輸出**:
```py
Sam has 12 red balls and 31 yellow balls
```
對于簡單的格式化,該技術是可以的,但是如果要在浮點數中指定精度怎么辦? 對于這種情況,您需要了解有關格式代碼的更多信息。 這是格式代碼的完整語法。
**語法**: `{[argument_index_or_keyword]:[width][.precision][type]}`
`type`可以與格式代碼一起使用:
| 格式碼 | 描述 |
| --- | --- |
| `d` | 用于整數 |
| `f` | 用于浮點數 |
| `b` | 用于二進制數 |
| `o` | 八進制數 |
| `x` | 八進制十六進制數 |
| `s` | 用于字符串 |
| `e` | 用于指數格式的浮點 |
以下示例將使事情更加清楚。
**示例 1**:
```py
>>> "Floating point {0:.2f}".format(345.7916732)
```
在這里,我們指定精度的`2`位,`f`用于表示浮點數。
**預期輸出**:
```py
Floating point 345.79
```
**示例 2**:
```py
>>> import math
>>> "Floating point {0:10.3f}".format(math.pi)
```
在這里,我們指定`3`精度數字,`10`表示寬度,`f`表示浮點數。
**預期輸出**:
```py
Floating point 3.142
```
**示例 3**:
```py
"Floating point pi = {0:.3f}, with {1:d} digit precision".format(math.pi, 3)
```
這里`{1:d}`中的`d`表示整數值。
**預期輸出**:
```py
Floating point pi = 3.142, with 3 digit precision
```
如果為整數`ValueError`指定精度,則僅在浮點數的情況下才需要指定精度。
**示例 5**:
```py
'Sam has {1:d} red balls and {0:d} yellow balls'.format(12, 31)
```
**預期輸出**:
```py
Sam has 31 red balls and 12 yellow balls
```
**示例 6**:
```py
"In binary 4 is {0:b}".format(4) # b for binary, refer to Fig 1.1
```
**預期輸出**:
```py
In binary 4 is 100
```
**示例 7**:
```py
array = [34, 66, 12]
"A = {0}, B = {1}, C = {2}".format(*array)
```
**預期輸出**:
```py
A = 34, B = 66, C = 12
```
**示例 8**:
```py
d = {
'hats' : 122,
'mats' : 42
}
"Sam had {hats} hats and {mats} mats".format(**d)
```
**預期輸出**:
```py
Sam had 122 hats and 42 mats
```
`format()`方法還支持關鍵字參數。
```py
'Sam has {red} red balls and {green} yellow balls'.format(red = 12, green = 31)
```
請注意,在使用關鍵字參數時,我們需要在`{}`內部使用參數,而不是數字索引。
您還可以將位置參數與關鍵字參數混合
```py
'Sam has {red} red balls, {green} yellow balls \
and {0} bats'.format(3, red = 12, green = 31)
```
格式化字符串的`format()`方法是一個非常新的方法,它是在 Python 2.6 中引入的。 您將在舊版代碼中看到另一種古老的技術,它允許您使用`%`運算符而不是`format()`方法來格式化字符串。
讓我們舉個例子。
```py
"%d pens cost = %.2f" % (12, 150.87612)
```
在這里,我們使用`%`左側的模板字符串。 我們使用`%`代替格式代碼的`{}`。 在`%`的右側,我們使用元組包含我們的值。 `%d`和`%.2f`被稱為格式說明符,它們以`%`開頭,后跟代表數據類型的字符。 例如,`%d`格式說明符是整數的占位符,類似地`%.2f`是浮點數的占位符。
因此,`%d`被替換為元組的第一值,即`12`,而`%.2f`被替換為第二值,即`150.87612`。
**預期輸出**:
```py
12 pens cost = 150.88
```
一些更多的例子。
**示例 1**:
新:
```py
"{0:d} {1:d} ".format(12, 31)
```
舊:
```py
"%d %d" % (12, 31)
```
**預期輸出**:
```py
12 31
```
**示例 2**:
New:
```py
"{0:.2f} {1:.3f}".format(12.3152, 89.65431)
```
Old:
```py
"%.2f %.3f" % (12.3152, 89.65431)
```
**預期輸出**:
```py
12.32 89.654
```
**示例 3**:
New:
```py
"{0:s} {1:o} {2:.2f} {3:d}".format("Hello", 71, 45836.12589, 45 )
```
Old:
```py
"%s %o %.2f %d" % ("Hello", 71, 45836.12589, 45 )
```
**預期輸出**:
```py
Hello 107 45836.13 45
```
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象