Python 的 str.format(~)
方法返回一個格式化字符串,其中提供的參數值插入到源字符串中的占位符位置。
參數
2種參數:
類型 |
說明 |
---|---|
Positional |
指定要替換的元素的位置 |
Keyword |
指定 key = value 來替換源字符串中的 |
返回值
返回格式化的字符串。
例子
位置參數
要使用位置參數的數字索引指定占位符 {}
以格式化字符串:
x = 'Meet {0}. {0} is {1} years old.'
x.format("Sky", 24)
'Meet Sky. Sky is 24 years old.'
"Sky"
作為第一個參數提供(即索引位置 0
),因此它被插入到源字符串中出現 {0}
的位置。由於 24
作為第二個參數提供(即索引位置 1
),因此它被插入到源字符串中的 {1}
處。
關鍵字參數
要分別插入 "Sky"
、 "Towner"
和 24
代替 {fname:<}
、 {lname}
和 {age}
占位符:
y = 'My name is {fname:<} {lname}. I am {age}.'
y.format(fname="Sky", lname="Towner", age=24)
'My name is Sky Towner. I am 24.'
請注意,我們為 {fname}
提供了格式化類型 :<
,它將在可用空間內 left-align 字符串。
格式化輸出
要將提供的值格式化為帶有千位分隔符的人口:
z = 'The population of this town is {population:,}.'
z.format(population=1200000))
The population of this town is 1,200,000.
通過提供 :,
格式化類型,總體值 1200000
在返回字符串中使用逗號千位分隔符進行格式化。
格式化類型列表
對齊選項
選項 |
意義 |
---|---|
|
強製字段在可用空間內左對齊。 |
|
強製字段在可用空間內右對齊。 |
|
強製將填充放置在符號(如果有)之後、數字之前。 |
|
強製字段在可用空間內居中。 |
標誌選項
選項 |
意義 |
---|---|
|
表示正數和負數均應使用符號。 |
|
指示符號隻能用於負數(這是默認行為)。 |
|
表示正數應使用前導空格,負數應使用減號。 |
字符串演示
類型 |
意義 |
---|---|
|
字符串格式。這是字符串的默認類型,可以省略。 |
|
與 |
整數表示
類型 |
意義 |
---|---|
|
二進製格式。輸出以 2 為基數的數字。 |
|
特點。在打印之前將整數轉換為相應的 unicode 字符。 |
|
十進製整數。輸出以 10 為基數的數字。 |
|
八進製格式。輸出以 8 為基數的數字。 |
|
十六進製格式。輸出以 16 為基數的數字,9 以上的數字使用小寫字母。 |
|
十六進製格式。輸出以 16 為基數的數字,9 以上的數字使用大寫字母。 |
|
數字。這與 |
|
與 |
浮點數和小數表示
類型 |
意義 |
---|---|
|
指數表示法。使用字母 |
|
指數表示法。與 |
|
定點表示法。將數字顯示為定點數。默認精度為 6。 |
|
定點表示法。與 |
|
通用格式。 |
|
通用格式。與 |
|
數字。這與 |
|
百分比。將數字乘以 100 並以固定 ( |
|
下劃線作為千位分隔符。 |
|
逗號作為千位分隔符。 |
相關用法
- Python String format_map()用法及代碼示例
- Python String format()用法及代碼示例
- Python String format_map方法用法及代碼示例
- Python String find方法用法及代碼示例
- Python String find()用法及代碼示例
- Python String count方法用法及代碼示例
- Python String isnumeric方法用法及代碼示例
- Python String Center()用法及代碼示例
- Python String zfill方法用法及代碼示例
- Python String rstrip方法用法及代碼示例
- Python String decode()用法及代碼示例
- Python String count()用法及代碼示例
- Python String join()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isalnum()用法及代碼示例
- Python String endswith方法用法及代碼示例
- Python String rsplit()用法及代碼示例
- Python String isidentifier()用法及代碼示例
- Python String startswith()用法及代碼示例
- Python String rjust方法用法及代碼示例
- Python String rpartition()用法及代碼示例
- Python String rpartition方法用法及代碼示例
- Python String ljust方法用法及代碼示例
- Python String splitlines()用法及代碼示例
- Python String upper()用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python String | format method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。