Python格式化輸出——format用法示例


format OR %

提到Python中的格式化輸出方法,一般來說有以下兩種方式:

print('hello %s' % 'world')
# hello world
print('hello {}'.format('world'))
# hello world

到底哪種好呢,反正對我來說,用了.format()之后就再也不想用%了。

  • format()不用理會數據類型,%s%f等等我記不完;
  • format()功能更豐富,填充方式,對齊方式都很靈活,讓你的打印效果更美觀;
  • format()是官方推薦的,%指不定就在未來版本中給廢棄掉了。

基本用法

print('{} {}'.format('hello', 'world'))  # 最基本的

print('{0} {1}'.format('hello', 'world'))  # 通過位置參數

print('{0} {1} {0}'.format('hello', 'world'))  # 單個參數多次輸出

"""輸出結果
hello world
hello world
hello world hello
"""

關鍵詞定位

# 通過關鍵詞參數
print('我的名字是{name},我今年{age}歲了。'.format(name='小明', age='12'))

# 與位置參數一樣,單個參數也能多次輸出
print('{name}說:"我的名字是{name},我今年{age}歲了。"'.format(name='小明', age='12'))

"""輸出結果
我的名字是小明,我今年12歲了。
小明說:"我的名字是小明,我今年12歲了。"
"""

可變參數

既然format()是一個方法,那是不是也接受*args**kwargs形式的傳參呢,答案是肯定的。

# 傳入list
data = ['hello', 'world']
print('{0} {1}'.format(*data))

# 傳入dict
data = {'name': '小明', 'age': 12}
print('我的名字是{name},我今年{age}歲了。'.format(**data))

# 混用
data_1 = ['hello', 'world']
data_2 = {'name': '小明', 'age': 12}
print('{0} {1} 我的名字是{name},我今年{age}歲了,{0}!'.format(*data_1, **data_2))

"""輸出結果
hello world
我的名字是小明,我今年12歲了。
hello world 我的名字是小明,我今年12歲了,hello!
"""

固定寬度

format()可以指定輸出寬度為多少,當字符串長度少於設定值的時候,默認用空格填充:

data = [{'name': 'Mary', 'college': 'Tsinghua University'},
        {'name': 'Micheal', 'college': 'Harvard University'},
        {'name': 'James', 'college': 'Massachusetts Institute of Technology'}]
# 固定寬度輸出
for item in data:
    print('{:10}{:40}'.format(item['name'], item['college']))

"""輸出結果
Mary      Tsinghua University                     
Micheal   Harvard University                      
James     Massachusetts Institute of Technology   

當然除了空格,我們也可以選擇其他字符來填充,譬如我想打印一條分割線,便可以選擇通過-來填充:

data = [{'name': 'Mary', 'college': 'Tsinghua University'},
        {'name': 'Micheal', 'college': 'Harvard University'},
        {'name': 'James', 'college': 'Massachusetts Institute of Technology'}]

# 固定寬度輸出
for item in data:
    # 每輸出一條記錄之前打印一條分割線
    # 選擇用其他字符來填充時需要指定對齊方式
    print('{:-^60}'.format('我是分割線'))
    print('{:10}{:40}'.format(item['name'], item['college']))

"""輸出結果
---------------------------我是分割線----------------------------
Mary      Tsinghua University                     
---------------------------我是分割線----------------------------
Micheal   Harvard University                      
---------------------------我是分割線----------------------------
James     Massachusetts Institute of Technology   
"""

對齊方式

format()支持左對齊,右對齊,居中,分別對應<>^,具體怎么使用我們看實例:

data = [{'name': 'Mary', 'college': 'Tsinghua University'},
        {'name': 'Micheal', 'college': 'Harvard University'},
        {'name': 'James', 'college': 'Massachusetts Institute of Technology'}]


print('{:-^50}'.format('居中'))
for item in data:
    print('{:^10}{:^40}'.format(item['name'], item['college']))

print('{:-^50}'.format('左對齊'))
for item in data:
    print('{:<10}{:<40}'.format(item['name'], item['college']))

print('{:-^50}'.format('右對齊'))
for item in data:
    print('{:>10}{:>40}'.format(item['name'], item['college']))

"""輸出結果
------------------------居中------------------------
   Mary             Tsinghua University           
 Micheal             Harvard University           
  James    Massachusetts Institute of Technology  
-----------------------左對齊------------------------
Mary      Tsinghua University                     
Micheal   Harvard University                      
James     Massachusetts Institute of Technology   
-----------------------右對齊------------------------
      Mary                     Tsinghua University
   Micheal                      Harvard University
     James   Massachusetts Institute of Technology
"""

數字格式化

常用的示例如下:

# 取小數點后兩位
num = 3.1415926
print('小數點后兩位:{:.2f}'.format(num))

# 帶+/-輸出
num = -3.1415926
print('帶正/負符號:{:+.2f}'.format(num))

# 轉為百分比
num = 0.34534
print('百分比:{:.2%}'.format(num))

# 科學計數法
num = 12305800000
print('科學計數法:{:.2e}'.format(num))

# ,分隔
num = 12305800000
print('","分隔:{:,}'.format(num))

# 轉為二進制
num = 15
print('二進制:{:b}'.format(num))

# 十六進制
num = 15
print('十六進制:{:x}'.format(num))

# 八進制
num = 15
print('八進制:{:o}'.format(num))

"""輸出結果
小數點后兩位:3.14
帶正/負符號:-3.14
百分比:34.53%
科學計數法:1.23e+10
","分隔:12,305,800,000
二進制:1111
十六進制:f
八進制:17
"""

輸出花括號

當然,如果我們想輸出的{}的時候怎么辦呢?

# 輸出花括號
print('我是{{{}}}'.format('Awesome_Tang'))

"""輸出結果
我是{Awesome_Tang}
"""

花式玩法

其實結合以上這些特性,我們可以來點好玩點,譬如說自己寫一個進度條:

import time

length = 1000
for i in range(1, length + 1):
    percent = i / length
    bar = '▉' * int(i // (length / 50))
    time.sleep(0.01)
    print('\r進度條:|{:<50}|{:>7.1%}'.format(bar, percent), end='')
print('\n')
  • 效果如下:

現在你覺得%str.format()哪個更好用呢?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM