format用法:
format()功能很強大,它把字符串當成一個模板,通過傳入的參數進行格式化,并且使用大括號‘{}’作為特殊字符代替‘%’。
使用方法由兩種:b.format(a)和format(a,b)。
python里format用法,1、基本用法
(1)不帶編號,即“{}”
(2)帶數字編號,可調換順序,即“{1}”、“{2}”
(3)帶關鍵字,即“{a}”、“{tom}”
python菜鳥教程。>>> print('{} {}'.format('千鋒','教育')) # 不帶字段
千鋒 教育
>>> print('{0} {1}'.format('千鋒','教育')) # 帶數字編號
千鋒 教育
python自帶的4個標準庫。>>> print('{0} {1} {0}'.format('千鋒','教育')) # 打亂順序
千鋒 教育 千鋒
>>> print('{1} {1} {0}'.format('千鋒','教育'))
教育 教育 千鋒
python數據清洗?>>> print('{a} {b} {a}'.format(a='千鋒',b='教育')) # 帶關鍵字
千鋒 教育 千鋒
2、進階用法
(1)< (默認)左對齊、> 右對齊、^ 中間對齊、= (只用于數字)在小數點后進行補齊
python的網絡請求標準庫有哪些?(2)取位數“{:4s}”、"{:.2f}"等
>>> print('{} and {}'.format('千鋒','教育')) # 默認左對齊
千鋒 and 教育
>>> print('{:10s} and {:>10s}'.format('千鋒','教育')) # 取10位左對齊,取10位右對齊
python中break和continue的區別,千鋒 and 教育
>>> print('{:^10s} and {:^10s}'.format('千鋒','教育')) # 取10位中間對齊
千鋒 and 教育
>>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小數
1.123 is 1.12
>>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小數,右對齊,取10位
1.123 is 1.12
3、多個格式化
'b' - 二進制。將數字以2為基數進行輸出。
>>> print('{0:b}'.format(3))
11
'c' - 字符。在打印之前將整數轉換成對應的Unicode字符串。
>>> print('{:c}'.format(20))
4
'd' - 十進制整數。將數字以10為基數進行輸出。
>>> print('{:d}'.format(20))
20
'o' - 八進制。將數字以8為基數進行輸出。
>>> print('{:o}'.format(20))
24
'x' - 十六進制。將數字以16為基數進行輸出,9以上的位數用小寫字母。
>>> print('{:x}'.format(20))
14
'e' - 冪符號。用科學計數法打印數字。用'e'表示冪。
>>> print('{:e}'.format(20))
2.000000e+01
'g' - 一般格式。將數值以fixed-point格式輸出。當數值特別大的時候,用冪形式打印。
>>> print('{:g}'.format(20.1))
20.1
'n' - 數字。當值為整數時和'd'相同,值為浮點數時和'g'相同。不同的是它會根據區域設置插入數字分隔符。
>>> print('{:f}'.format(20))
20.000000
>>> print('{:n}'.format(20))
20
'%' - 百分數。將數值乘以100然后以fixed-point('f')格式打印,值后面會有一個百分號。
>>> print('{:%}'.format(20))
2000.000000%
4、通過位置匹配參數
>>> '{0}, {1}, {2}'.format('北京', '千鋒', '教育')
'北京,千鋒,教育'
>>> '{}, {}, {}'.format('北京', '千鋒', '教育') # 3.1+版本支持
'北京,千鋒,教育'
>>> '{2}, {1}, {0}'.format('北京', '千鋒', '教育')
'教育,千鋒,北京'
>>> '{2}, {1}, {0}'.format(*'北京千') # 可打亂順序
'千, 京, 北'
>>> '{0}{1}{0}'.format('千鋒', '教育') # 可重復
'千鋒教育千鋒'
5、通過名字匹配參數
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
另,可在字符串前加f以達到格式化的目的,在{}里加入對象,此為format的另一種形式:
name = 'qianfeng'
age = 18
sex = 'man'
job = "IT"
salary = 9999.99
print(f'my name is {name.capitalize()}.')
print(f'I am {age:*^10} years old.')
print(f'I am a {sex}')
print(f'My salary is {salary:10.3f}')
# 結果
my name is Qianfeng.
I am ****18**** years old.
I am a man
My salary is 9999.990
【重要消息】本文是軟件測試系列知識中python腳本語言中的一篇,筆者認為本部分全面的知識應該包含如下圖所示的內容:
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态