format 用法詳解
print('hello {0} i am {1}'.format('world','python')) # 輸入結果:hello world i am python print('hello {} i am {}'.format('world','python') ) #輸入結果:hello world i am python print('hello {0} i am {1} . a now language-- {1}'.format('world','python') # 輸出結果:hello world i am python . a now language-- python
obj = 'world' name = 'python' print('hello, {obj} ,i am {name}'.format(obj = obj,name = name)) # 輸入結果:hello, world ,i am python
list=['world','python'] print('hello {names[0]} i am {names[1]}'.format(names=list))# 輸出結果:hello world i am python print('hello {0[0]} i am {0[1]}'.format(list)) #輸出結果:hello world i am python
dict={‘obj’:’world’,’name’:’python’} print(‘hello {names[obj]} i am {names[name]}’.format(names=dict)) # hello world i am python
6.使用魔法參數
args = [‘,’,’inx’] kwargs = {‘obj’: ‘world’, ‘name’: ‘python’} print(‘hello {obj} {} i am {name}’.format(*args, **kwargs)) # 輸入結果:hello world , i am python
注意:魔法參數跟你函數中使用的性質是一樣的:這里format(*args, **kwargs)) 等價於:format(‘,’,’inx’,obj = ‘world’,name = ‘python’)
format 格式轉換
數字 | 格式 | 輸出 | 描述 |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | 保留小數點后兩位 |
3.1415926 | {:+.2f} | 3.14 | 帶符號保留小數點后兩位 |
-1 | {:+.2f} | -1 | 帶符號保留小數點后兩位 |
2.71828 | {:.0f} | 3 | 不帶小數 |
1000000 | {:,} | 1,000,000 | 以逗號分隔的數字格式 |
0.25 | {:.2%} | 25.00% | 百分比格式 |
1000000000 | {:.2e} | 1.00E+09 | 指數記法 |
25 | {0:b} | 11001 | 轉換成二進制 |
25 | {0:d} | 25 | 轉換成十進制 |
25 | {0:o} | 31 | 轉換成八進制 |
25 | {0:x} | 19 | 轉換成十六進制 |
5 | {:0>2} | 05 | 數字補零(填充左邊, 寬度為2) |
5 | {:x<4} | 5xxx | 數字補x (填充右邊, 寬度為4) |
10 | {:x^4} | x10x | 數字補x (填充兩邊,優先左邊, 寬度為4) |
13 | {:10} | 13 | 右對齊 (默認, 寬度為10) |
13 | {:<10} | 13 | 左對齊 (寬度為10) |
13 | {:^10} | 13 | 中間對齊 (寬度為10) |
b、d、o、x分別是二進制、十進制、八進制、十六進制。
其它用法
1.轉義“{}”
print('{{hello}} {{{0}}}'.format('world')) #輸出結果:{hello} {world}
name = 'InX' hello = 'hello,{} welcome to python world!!!'.format #定義一個問候函數 hello(name) # 輸入結果:hello,inx welcome to python world!!!
from datetime import datetime now=datetime.now() print '{:%Y-%m-%d %X}'.format(now) # 輸出結果:2017-07-24 16:51:42
print('hello {0:>{1}} '.format('world',10)) ##輸出結果:hello world