Python格式化輸出(%用法和format用法)

整數的輸出

  • %o——Oct八進制
  • %d——Dec十進制
  • %x——Hex十六進制

浮點數(小數)的輸出

格式化輸出

>>> awsl=2.333
>>> print('%f'%awsl)	#默認保留6位小數
2.333000
>>> print('%.1f'%awsl)	#取1位小數
2.3
>>> print('%e'%awsl)	#默認6位小數,用科學計數法
2.333000e+00
>>> print('%.2e'%awsl)	#取2位小數,用科學計數法
2.33e+00
>>> print('%g'%2.3333333)#默認6位有效數字
2.33333
>>> print('%.5g'%233.33333)#取5位有效數字
233.33
>>> print('%.2g'%2333.3333)#取2位有效數字,自動轉換爲科學計數法
2.3e+03

內置round()

round(number[, ndigits])
參數:
number - 這是一個數字表達式。
ndigits - 表示從小數點到最後四捨五入的位數。默認值爲0。
返回值
該方法返回x的小數點舍入爲n位數後的值。

  • round()函數只有一個參數,不指定位數的時候,返回一個整數,而且是最靠近的整數,類似於四捨五入
  • 當指定取捨的小數點位數的時候,一般情況也是使用四捨五入的規則
  • 但是碰到.5的情況時,如果要取捨的位數前的小數是奇數,則直接捨棄,如果是偶數則向上取捨。

注:“.5”這個是一個“坑”,且python2和python3出來的接口有時候是不一樣的,儘量避免使用round()函數吧

 >>> round(1.1125)  # 四捨五入,不指定位數,取整
 1
 >>> round(1.1135,3)  # 取3位小數,由於3爲奇數,則向下“舍”
 1.113
 >>> round(1.1125,3)  # 取3位小數,由於2爲偶數,則向上“入”
 1.113
>>> round(2.675,2)	# 取2位有效小數
2.67

注:round(2.675,2)的結果,結果應該是2.68的,但它偏偏是2.67,爲什麼?這跟浮點數
的精度有關。在機器中浮點數不一定能精確表達,換算成一串 1和0後可能是無限位數的,
機器已經做出了截斷處理。因此在機器中保存的2.675這個數字就比實際數字要小那麼一點
點。這一點點就導致了它離2.67要更近一點點,所以保留兩位小數時就近似到了2.67。

字符串輸出

  • %s
  • %10s——右對齊,佔位符10位
  • %-10s——左對齊,佔位符10位
  • %.2s——截取2位字符串
  • %10.2s——10位佔位符,截取兩位字符串
>>> print('%s' % 'hello world')  # 字符串輸出
hello world
>>> print('%20s' % 'hello world')  # 右對齊,取20位,不夠則補位
         hello world
>>> print('%-20s' % 'hello world')  # 左對齊,取20位,不夠則補位
hello world         
>>> print('%.2s' % 'hello world')  # 取2位
he
>>> print('%10.2s' % 'hello world')  # 右對齊,取2位
        he
>>> print('%-10.2s' % 'hello world')  # 左對齊,取2位
he

格式化輸出多個變量

>>> hhh=2333
>>> awsl=2.333
>>> print('%d+%f=%f'%(hhh,awsl,hhh+awsl))
2333+2.333000=2335.333000

格式化符號大全

符 號 描述
%c 格式化字符及其ASCII碼
%s 格式化字符串
%d 格式化整數
%u 格式化無符號整型
%o 格式化無符號八進制數
%x 格式化無符號十六進制數
%X 格式化無符號十六進制數(大寫)
%f 格式化浮點數字,可指定小數點後的精度
%e 用科學計數法格式化浮點數
%E 作用同%e,用科學計數法格式化浮點數
%g 浮點型數據 會去掉多餘的零 至多保留6位
%G 浮點型數據 會去掉多餘的零 至多保留6位
%p 用十六進制數格式化變量的地址

格式化操作符輔助指令:

符號 描述
* 定義寬度或者小數點精度
- 用做左對齊
+ 在正數前面顯示加號( + )
< sp > 在正數前面顯示空格
# 在八進制數前面顯示零(‘0’),在十六進制前面顯示’0x’或者’0X’(取決於用的是’x’還是’X’)
0 顯示的數字前面填充’0’而不是默認的空格
% ‘%%‘輸出一個單一的’%’
(var) 映射變量(字典參數)
m.n. m 是顯示的最小總寬度,n 是小數點後的位數(如果可用的話)

format用法

相對基本格式化輸出採用‘%’的方法,format()功能更強大,該函數把字符串當成一個模板,通過傳入的參數進行格式化,並且使用大括號‘{}’作爲特殊字符代替‘%’

位置匹配

  1. 不帶編號,即“{}”
  2. 帶數字編號,可調換順序,即“{1}”、“{2}”
  3. 帶關鍵字,即“{a}”、“{tom}”
>>> print('{} {}'.format('zeruns','blog.zeruns.tech'))  # 不帶字段
zeruns blog.zeruns.tech
>>> print('{0} {1}'.format('hello','world'))  # 帶數字編號
hello world
>>> print('{1}{0}'.format('blog.zeruns.tech','https://'))
https://blog.zeruns.tech
>>> print('{0} {1} {0}'.format('hello','world'))  # 打亂順序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  # 帶關鍵字
world hello world

#通過位置匹配
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+版本支持
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')  # 可打亂順序
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')  # 可重複
'abracadabra'

#通過名字匹配
>>> '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'

#通過下標或key匹配參數
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
>>> a = {'a': 'test_a', 'b': 'test_b'}
>>> 'X: {0[a]};  Y: {0[b]}'.format(a)
'X: test_a;  Y: test_b'

格式轉換

  • ‘b’ - 二進制。將數字以2爲基數進行輸出。
  • ‘c’ - 字符。在打印之前將整數轉換成對應的Unicode字符串。
  • ‘d’ - 十進制整數。將數字以10爲基數進行輸出。
  • ‘o’ - 八進制。將數字以8爲基數進行輸出。
  • ‘x’ - 十六進制。將數字以16爲基數進行輸出,9以上的位數用小寫字母。
  • ‘e’ - 冪符號。用科學計數法打印數字。用’e’表示冪。
  • ‘g’ - 一般格式。將數值以fixed-point格式輸出。當數值特別大的時候,用冪形式打印。
  • ‘f’ - 浮點數。將數字以浮點數形式輸出,默認6位小數。
  • ‘n’ - 數字。當值爲整數時和’d’相同,值爲浮點數時和’g’相同。不同的是它會根據區域設置插入數字分隔符。
  • ‘%’ - 百分數。將數值乘以100然後以fixed-point(‘f’)格式打印,值後面會有一個百分號。
>>> print('{0:b}'.format(3))
11
>>> print('{:c}'.format(20))

>>> print('{:d}'.format(20))
20
>>> print('{:o}'.format(20))
24
>>> print('{:x}'.format(20))
14
>>> print('{:e}'.format(20))
2.000000e+01
>>> print('{:g}'.format(20.1))
20.1
>>> print('{:f}'.format(20))
20.000000
>>> print('{:n}'.format(20))
20
>>> print('{:%}'.format(20))
2000.000000%

format的用法變形

# a.format(b)
>>> "{0} {1}".format("hello","world")
'hello world'


# f"xxxx"
# 可在字符串前加f以達到格式化的目的,在{}里加入對象,此爲format的另一種形式:

>>> a = "hello"
>>> b = "world"
>>> f"{a} {b}"
'hello world'



name = 'jack'
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 Jack.
I am ****18**** years old.
I am a man
My salary is   9999.990

原文:https://blog.zeruns.tech/index.php/archives/324/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章