新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:pythonformat是什么
Python中FORMAT主要是用來格式化字符串的。

format用法相對基本格式化輸出采用‘%’的方法,format()功能更強大,該函數(shù)把字符串當成一個模板,通過傳入的參數(shù)進行格式化,
并且使用大括號‘{}’作為特殊字符代替‘%’
使用方法由兩種:b.format(a)和format(a,b)。
1、基本用法
(1)不帶編號,即“{}”
(2)帶數(shù)字編號,可調(diào)換順序,即“{1}”、“{2}”
(3)帶關鍵字,即“{a}”、“{tom}”
1 >>> print('{} {}'.format('hello','world')) # 不帶字段
2 hello world
3 >>> print('{0} {1}'.format('hello','world')) # 帶數(shù)字編號
4 hello world
5 >>> print('{0} {1} {0}'.format('hello','world')) # 打亂順序
6 hello world hello
7 >>> print('{1} {1} {0}'.format('hello','world'))
2、進階用法
(1)< (默認)左對齊、> 右對齊、^ 中間對齊、= (只用于數(shù)字)在小數(shù)點后進行補齊
(2)取位數(shù)“{:4s}”、"{:.2f}"等
1 >>> print('{} and {}'.format('hello','world')) # 默認左對齊
2 hello and world
3 >>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左對齊,取10位右對齊
4 hello and world
5 >>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中間對齊
6 hello and world
7 >>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小數(shù)
8 1.123 is 1.12
9 >>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小數(shù),右對齊,取10位
10 1.123 is 1.12
python學習網(wǎng),大量的免費python學習視頻,歡迎在線學習!
名稱欄目:創(chuàng)新互聯(lián)Python教程:pythonformat是什么
網(wǎng)站路徑:http://www.5511xx.com/article/dpgjcio.html


咨詢
建站咨詢
