參考網站:https://www.cnblogs.com/czqq/p/6108557.html
感覺Python學起來有些亂,特別是格式化輸出這一塊,而格式化輸出勢必涉及到占位符的使用
今天就來總結一下占位符%的使用
%[(name)][flags][width].[precision]typecode
不要被上面這一大串給嚇唬到了,實際上這也是Python的魅力所在
一個個分析
1、(name)屬性,它是用來傳入字典值的
示例:
print('hi %(name)s' %{'name':'jack'})
結果: hi jack
2、[flags]屬性,作為用戶對一些格式的選擇,只有固定的幾個值,以下
- + 右對齊;正數前加正好,負數前加負號;
- - 左對齊;正數前無符號,負數前加負號;
- 空格 右對齊;正數前加空格,負數前加負號;
- 0 右對齊;正數前無符號,負數前加負號;用0填充空白處
示例:
print('the number is %-d %-d' %(+250,-250)) print('the number is %+d %+d' %(+250,-250)) print('the number is %0d %0d' %(+250,-250)) print('the number is % d % d' %(+250,-250))
結果:
the number is 250 -250
the number is +250 -250
the number is 250 -250
the number is 250 -250
3、[width]屬性,根據名字就可以知道指的是寬度
示例:
print('my salary is %4d yuan in this month' %(2504637))#set the width to four print('my salary is %9d yuan in this month' %(2504637))#set the width to nine
結果為:
說明如果設置寬度低於實際字符寬度時,會按照實際的寬度來輸出
但是如果設置寬度高於字符寬度時,會按照設置的寬度輸出,空白符自動補位,右對齊
4、.[precision]屬性,很簡單,與c和c++相似,用來表示輸出小數點后幾位
示例:
print('the answer to the question is %.3f' % (12.34567))
結果為:
the answer to the question is 12.346
這里就不用解釋了
5、typecod屬性,用於指定輸出類型
- s,獲取傳入對象的__str__方法的返回值,並將其格式化到指定位置
- r,獲取傳入對象的__repr__方法的返回值,並將其格式化到指定位置
- c,整數:將數字轉換成其unicode對應的值,10進制范圍為 0 <= i <= 1114111(py27則只支持0-255);字符:將字符添加到指定位置
- o,將整數轉換成 八 進制表示,並將其格式化到指定位置
- x,將整數轉換成十六進制表示,並將其格式化到指定位置
- d,將整數、浮點數轉換成 十 進制表示,並將其格式化到指定位置
- e,將整數、浮點數轉換成科學計數法,並將其格式化到指定位置(小寫e)
- E,將整數、浮點數轉換成科學計數法,並將其格式化到指定位置(大寫E)
- f, 將整數、浮點數轉換成浮點數表示,並將其格式化到指定位置(默認保留小數點后6位)
- F,同上
- g,自動調整將整數、浮點數轉換成 浮點型或科學計數法表示(超過6位數用科學計數法),並將其格式化到指定位置(如果是科學計數則是e;)
- G,自動調整將整數、浮點數轉換成 浮點型或科學計數法表示(超過6位數用科學計數法),並將其格式化到指定位置(如果是科學計數則是E;)
- %,當字符串中存在格式化標志時,需要用 %%表示一個百分號
這里選一個經典示例:
比如想一句話中多種格式化輸出,多個占位符 %問題,用個‘+’號就可以解決
print('a is %s ' %('123')+'b is %s'%('456')) print('the speed of %(obj)s '%{'obj':'light'}+'is %10.2f meters per second' %(299792458))
結果:
a is 123 b is 456
the speed of light is 299792458.00 meters per second
這就是%號占位符的總結,謝謝各位看客,覺得好的點個贊哦!!!
轉載請注明https://www.cnblogs.com/gambler/p/9567165.html