Usage Example Python formatted output --format

format OR %

Python method mentioned in the formatted output, there are two general ways:

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

In the end what is good, for me anyway, use the .format()following will not want to use %up.

  • format()Ignore data types %s, %fand so I remember not finish;
  • format()More feature-rich, filling mode, alignment is very flexible and allows you to print the effect is more beautiful;
  • format()It is the official recommendation, %Zhibuding in future releases to the waste out.

    Basic Usage

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

print('{0} {1}'.format('hello', 'world'))  # 通过位置参数

print('{0} {1} {0}'.format('hello', 'world'))  # 单个参数多次输出

"""输出结果
hello world
hello world
hello world hello
"""

Keyword spotting

# 通过关键词参数
print('我的名字是{name},我今年{age}岁了。'.format(name='小明', age='12'))

# 与位置参数一样,单个参数也能多次输出
print('{name}说:"我的名字是{name},我今年{age}岁了。"'.format(name='小明', age='12'))

"""输出结果
我的名字是小明,我今年12岁了。
小明说:"我的名字是小明,我今年12岁了。"
"""

variable parameter

Since it format()is a method, it is not also accept *argsand **kwargsforms of mass participation, the answer is yes.

# 传入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!
"""

Fixed-width

format()You can specify how much output width, when the set value is less than the string length, the default padded with spaces:

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   

Of course in addition to the space, we can also choose other characters to fill, for example, I want to print a split line, you can choose by -to fill:

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   
"""

Alignment

format()Support left justified, right justified, centered, respectively <, , >, ^we look at how to use specific examples:

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
"""

Digital Format

Commonly used examples are as follows:

# 取小数点后两位
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
"""

Output braces

Of course, if we want to output the {}time how to do it?

# 输出花括号
print('我是{{{}}}'.format('Awesome_Tang'))

"""输出结果
我是{Awesome_Tang}
"""

Fancy Play

In fact, combined with these features, we can point to something fun to do, say, write a progress bar:

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')
  • Results are as follows:

    ***

Now you feel %and str.format()what better use is it?

Guess you like

Origin www.cnblogs.com/awesometang/p/12005740.html