Python格式化
1. 概述
Python2.6 開始蝇棉,新增了一種格式化字符串的函數(shù) str.format()谍珊,它增強了字符串格式化的功能。
基本語法是通過 {} 和 : 來代替以前的 % 。
format 函數(shù)可以接受不限個參數(shù)鸥印,位置可以不按順序恭陡。
# 不設(shè)置指定位置蹬音,按默認順序
print("{} {}".format("hello","world"))
#output:hello world
# 設(shè)置指定位置
print("{0} {1}! {0} {1}!".format("hello","world"))
#output:hello world! hello world!
2. 實例
設(shè)置占位
print("身高:{height},體重{weight}".format(height="182",weight="75kg"))
#output:身高:182休玩,體重75kg
通過字典設(shè)置參數(shù)
site = {"name": "Google", "url": "www.google.com","ip":"192.168.12.45"}
# print("網(wǎng)站名:{name},地址:{url}".format(name = site["name"],url = site["url"]))
print("網(wǎng)站名:{name},地址:{url}, ip:{ip}".format(**site))
#網(wǎng)站名:Google,地址:www.google.com, ip:192.168.12.45
通過列表索引設(shè)置參數(shù)
l = ["谷歌","www.google.com"]
print("網(wǎng)站名:{0[0]}著淆,地址:{0[1]}".format(l)) #0是必須的
3. 數(shù)字格式化
#數(shù)字格式化
print("{:.2f}".format(3.1415926))
#3.14
#進制
print("{:b}".format(2))
#10
數(shù)字 | 格式 | 輸出 | 描述 |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | 保留小數(shù)點后兩位 |
3.1415926 | {:+.2f} | +3.14 | 帶符號保留小數(shù)點后兩位 |
-1 | {:+.2f} | -1.00 | 帶符號保留小數(shù)點后兩位 |
2.71828 | {:.0f} | 3 | 不帶小數(shù) |
5 | {:0>2d} | 05 | 數(shù)字補零 (填充左邊, 寬度為2) |
5 | {:x<4d} | 5xxx | 數(shù)字補x (填充右邊, 寬度為4) |
10 | {:x<4d} | 10xx | 數(shù)字補x (填充右邊, 寬度為4) |
1000000 | {:,} | 1,000,000 | 以逗號分隔的數(shù)字格式 |
0.25 | {:.2%} | 25.00% | 百分比格式 |
1000000000 | {:.2e} | 1.00e+09 | 指數(shù)記法 |
13 | {:10d} | 13 | 右對齊 (默認, 寬度為10) |
13 | {:<10d} | 13 | 左對齊 (寬度為10) |
13 | {:^10d} | 13 | 中間對齊 (寬度為10) |
11 | '{:b}'.format(11) '{:d}'.format(11) '{:o}'.format(11) '{:x}'.format(11) '{:#x}'.format(11) '{:#X}'.format(11) | 1011 11 13 b 0xb 0XB | 進制 |
^, <, > 分別是居中、左對齊拴疤、右對齊永部,后面帶寬度, : 號后面帶填充的字符呐矾,只能是一個字符苔埋,不指定則默認是用空格填充。
- 表示在正數(shù)前顯示 +蜒犯,負數(shù)前顯示 -组橄; (空格)表示在正數(shù)前加空格
b、d愧薛、o晨炕、x 分別是二進制、十進制毫炉、八進制瓮栗、十六進制。
此外我們可以使用大括號 {} 來轉(zhuǎn)義大括號,如下實例: