參考資料:https://www.runoob.com/python/att-string-format.html
在學習Python的時候碰到了一個很有趣的格式化輸入的技巧,下面記錄在此。
Python2.6 開始,新增了一種格式化字符串的函數 str.format(),它增強了字符串格式化的功能。
基本語法是通過 {} 和 : 來代替以前的 % 。
format 函數可以接受不限個參數,位置可以不按順序。
實例:
>>>"{} {}".format("hello", "world") # 不設置指定位置,按默認順序 'hello world' >>> "{0} {1}".format("hello", "world") # 設置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 設置指定位置 'world hello world'
也可以設置參數:
#!/usr/bin/python # -*- coding: UTF-8 -*- print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com")) # 通過字典設置參數 site = {"name": "菜鳥教程", "url": "www.runoob.com"} print("網站名:{name}, 地址 {url}".format(**site)) # 通過列表索引設置參數 my_list = ['菜鳥教程', 'www.runoob.com'] print("網站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的
輸出結果均為:"網站名:菜鳥教程, 地址 www.runoob.com"
下面是str.format()格式化數字的多種方法:
>>> print("{:.2f}".format(3.1415926)); 3.14
數字 | 格式 | 輸出 | 描述 |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | 保留小數點后兩位 |
3.1415926 | {:+.2f} | +3.14 | 帶符號保留小數點后兩位 |
-1 | {:+.2f} | -1.00 | 帶符號保留小數點后兩位 |
2.71828 | {:.0f} | 3 | 不帶小數 |
5 | {:0>2d} | 05 | 數字補零 (填充左邊, 寬度為2) |
5 | {:x<4d} | 5xxx | 數字補x (填充右邊, 寬度為4) |
10 | {:x<4d} | 10xx | 數字補x (填充右邊, 寬度為4) |
1000000 | {:,} | 1,000,000 | 以逗號分隔的數字格式 |
0.25 | {:.2%} | 25.00% | 百分比格式 |
1000000000 | {:.2e} | 1.00e+09 | 指數記法 |
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 |
進制 |