提到 Python 中的格式化输出方法, 一般来说有以下两种方式:
1)%
格式说明由 % 和格式字符组成, 如 %f,%s,%d, 它的作用是将数据按照指定的格式输出. 格式说明是由 "%" 字符开始的.
- #1. 输出字符串 %s
- print('my name is %s' % ('xiaoming'))
- #2. 整型输出 %d
- print('My sister is %s, Her age is %d,'%('Lina',18))
- #3. 输出浮点数
- print('Her height is %f m' % (1.6500))
- #4. 保留 2 位小数
- print('His height is %.2f m' % (1.6500))
- #5. 指定占位符宽度
- print('name:%10s age:%10d height:%5.2f' % ('Lina',18,1.6500))
- #6. 指定占位符宽度(左对齐)
- print('name:%-10s age:%-10d height:%-5.2f' % ('Lina',18,1.6500))
- #7. 字符串截取
- print('%.5s' % ('hello word'))# 截取前 5 个字符
- '''
- 运行结果
- my name is xiaoming
- My sister is Lina, Her age is 18,
- Her height is 1.650000 m
- His height is 1.65 m
- name: Lina age: 18 height: 1.65
- name:Lina age:18 height:1.65
- hello
- '''
- View Code
- 2) format
Python2.6 开始, 新增了一种格式化字符串的函数 str.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
- """
- View Code
关键词定位
- # 通过关键词参数
- print('我的名字是 {name}, 我今年{age} 岁了.'.format(name='Linda', age='18'))
- # 与位置参数一样, 单个参数也能多次输出
- print('{name}说:" 我的名字是 {name}, 我今年{age} 岁了."'.format(name='linda', age='18'))
- """ 输出结果
- 我的名字是 linda, 我今年 18 岁了.
- linda 说:"我的名字是 Linda, 我今年 18 岁了."
- """
- View Code
可变参数
可传入 list,dic 类型
- # 传入 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!
- """
- View Code
固定宽度
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
View Code
当然除了空格, 我们也可以选择其他字符来填充, 譬如我想打印一条分割线, 便可以选择通过 - 来填充:
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
"""
View Code
对齐方式
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
"""
View Code
数字格式化
常用的示例如下:
# 取小数点后两位
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
"""
View Code
可以设置参数
print("网站名:{name}, 地址 {url}".format(name="博客园", url="https://home.cnblogs.com/u/yaner2018/"))
# 通过字典设置参数
site = {"name": "博客园", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
my_list = ['博客园', 'https://home.cnblogs.com/u/yaner2018/']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
'''
网站名: 博客园, 地址 https://home.cnblogs.com/u/yaner2018/
网站名: 博客园, 地址 https://home.cnblogs.com/u/yaner2018/
网站名: 博客园, 地址 https://home.cnblogs.com/u/yaner2018/
'''
View Code
可以向 str.format() 传入对象:
- class demo(object):
- def __init__(self, value):
- self.value = value
- my_value = demo(6)
- print('value 为: {0.value}'.format(my_value)) # "0" 是可选的
- View Code
----------------------------------------- 总结 -----------------------------------------------------
^, <, > 分别是居中, 左对齐, 右对齐, 后面带宽度, : 号后面带填充的字符, 只能是一个字符, 不指定则默认是用空格填充.
+ 表示在正数前显示 +, 负数前显示 -;(空格)表示在正数前加空格
b,d,o,x 分别是二进制, 十进制, 八进制, 十六进制.
------------------------------------------------------------------------------------------------
此外我们可以使用大括号 {} 来转义大括号, 如下实例:
- print("{} 对应的位置是 {{0}}".format("runoob"))
- # 输出:
- #runoob 对应的位置是 {
- 0
- }
python 格式化输出(% VS format)
来源: http://www.bubuko.com/infodetail-3266070.html