Python format() 函数
生活随笔
收集整理的這篇文章主要介紹了
Python format() 函数
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Python2.6 開始,新增了一種格式化字符串的函數(shù)?format() ,它增強(qiáng)了字符串格式化的功能。
基本語(yǔ)法是通過(guò)?{}?和?:?來(lái)代替以前的?%?。
format () 函數(shù)可以接受不限個(gè)參數(shù),位置可以不按順序。
實(shí)例
>>>"{} {}".format("hello", "world") # 不設(shè)置指定位置,按默認(rèn)順序 'hello world'>>> "{0} {1}".format("hello", "world") # 設(shè)置指定位置 'hello world'>>> "{1} {0} {1}".format("hello", "world") # 設(shè)置指定位置 'world hello world'也可以設(shè)置參數(shù):
實(shí)例
#!/usr/bin/python # -*- coding: UTF-8 -*-print("網(wǎng)站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com"))print("網(wǎng)站名:{0}, 地址 {1}".format('菜鳥教程','www.runoob.com'))# 通過(guò)字典設(shè)置參數(shù) site = {"name": "菜鳥教程", "url": "www.runoob.com"} print("網(wǎng)站名:{name}, 地址 {url}".format(**site))# 通過(guò)列表索引設(shè)置參數(shù) my_list = ['菜鳥教程', 'www.runoob.com'] print("網(wǎng)站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是可選的輸出結(jié)果為:
網(wǎng)站名:菜鳥教程, 地址 www.runoob.com 網(wǎng)站名:菜鳥教程, 地址 www.runoob.com 網(wǎng)站名:菜鳥教程, 地址 www.runoob.com 網(wǎng)站名:菜鳥教程, 地址 www.runoob.com也可以向?format() 函數(shù)傳入對(duì)象:
實(shí)例
#!/usr/bin/python # -*- coding: UTF-8 -*-class AssignValue(object):def __init__(self, value):self.value = value my_value = AssignValue(6) print('value 為: {0.value}'.format(my_value)) # "0" 是可選的輸出結(jié)果為:
value 為: 6數(shù)字格式化
下表展示了 str.format() 格式化數(shù)字的多種方法:
>>> print("{:.2f}".format(3.1415926)); 3.14| 3.1415926 | {:.2f} | 3.14 | 保留小數(shù)點(diǎn)后兩位 |
| 3.1415926 | {:+.2f} | +3.14 | 帶符號(hào)保留小數(shù)點(diǎn)后兩位 |
| -1 | {:+.2f} | -1.00 | 帶符號(hào)保留小數(shù)點(diǎn)后兩位 |
| 2.71828 | {:.0f} | 3 | 不帶小數(shù) |
| 5 | {:0>2d} | 05 | 數(shù)字補(bǔ)零 (填充左邊, 寬度為2) |
| 5 | {:x<4d} | 5xxx | 數(shù)字補(bǔ)x (填充右邊, 寬度為4) |
| 10 | {:x<4d} | 10xx | 數(shù)字補(bǔ)x (填充右邊, 寬度為4) |
| 1000000 | {:,} | 1,000,000 | 以逗號(hào)分隔的數(shù)字格式 |
| 0.25 | {:.2%} | 25.00% | 百分比格式 |
| 1000000000 | {:.2e} | 1.00e+09 | 指數(shù)記法 |
| 13 | {:10d} | ????????13 | 右對(duì)齊 (默認(rèn), 寬度為10) |
| 13 | {:<10d} | 13 | 左對(duì)齊 (寬度為10) |
| 13 | {:^10d} | ????13 | 中間對(duì)齊 (寬度為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 | 進(jìn)制 |
^,?<,?>?分別是居中、左對(duì)齊、右對(duì)齊,后面帶寬度,?:?號(hào)后面帶填充的字符,只能是一個(gè)字符,不指定則默認(rèn)是用空格填充。
+?表示在正數(shù)前顯示?+,負(fù)數(shù)前顯示?-;??(空格)表示在正數(shù)前加空格
b、d、o、x 分別是二進(jìn)制、十進(jìn)制、八進(jìn)制、十六進(jìn)制。
此外我們可以使用大括號(hào)?{}?來(lái)轉(zhuǎn)義大括號(hào),如下實(shí)例:
實(shí)例
#!/usr/bin/python # -*- coding: UTF-8 -*-print ("{} 對(duì)應(yīng)的位置是 {{0}}".format("runoob"))輸出結(jié)果為:
runoob 對(duì)應(yīng)的位置是 {0}總結(jié)
以上是生活随笔為你收集整理的Python format() 函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ExtJS + Gears
- 下一篇: hadoop之 YARN配置参数剖析—