python赋值语句的一般格式为_python 格式化输出(% VS format)

提到Python中的格式化输出方法,一般来说有以下两种方式:

1)%

格式说明由%和格式字符组成,如%f,%s,%d,它的作用是将数据按照指定的格式输出。格式说明是由“%”字符开始的。

ContractedBlock.gif

ExpandedBlockStart.gif

1 #1.输出字符串%s

2 print('my name is %s' % ('xiaoming'))3

4 #2.整型输出%d

5 print('My sister is %s, Her age is %d,'%('Lina',18))6

7 #3.输出浮点数

8 print('Her height is %f m' % (1.6500))9

10 #4.保留2位小数

11 print('His height is %.2f m' % (1.6500))12

13 #5.指定占位符宽度

14 print('name:%10s age:%10d height:%5.2f' % ('Lina',18,1.6500))15

16 #6.指定占位符宽度(左对齐)

17 print('name:%-10s age:%-10d height:%-5.2f' % ('Lina',18,1.6500))18

19 #7.字符串截取

20 print('%.5s' % ('hello word'))#截取前5个字符

21

22 '''

23 运行结果24 my name is xiaoming25 My sister is Lina, Her age is 18,26 Her height is 1.650000 m27 His height is 1.65 m28 name: Lina age: 18 height: 1.6529 name:Lina age:18 height:1.6530 hello31

32

33 '''

View Code

2) format

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

基本用法

ContractedBlock.gif

ExpandedBlockStart.gif

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

2

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

4

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

6

7 """输出结果8 hello world9 hello world10 hello world hello11 """

View Code

关键词定位

ContractedBlock.gif

ExpandedBlockStart.gif

1 #通过关键词参数

2 print('我的名字是{name},我今年{age}岁了。'.format(name='Linda', age='18'))3

4 #与位置参数一样,单个参数也能多次输出

5 print('{name}说:"我的名字是{name},我今年{age}岁了。"'.format(name='linda', age='18'))6

7 """输出结果8 我的名字是linda,我今年18岁了。9 linda说:"我的名字是Linda,我今年18岁了。"10 """

View Code

可变参数

可传入list、dic类型

ContractedBlock.gif

ExpandedBlockStart.gif

1 #传入list

2 data = ['hello', 'world']3 print('{0} {1}'.format(*data))4

5 #传入dict

6 data = {'name': '小明', 'age': 12}7 print('我的名字是{name},我今年{age}岁了。'.format(**data))8

9 #混用

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

14 """输出结果15 hello world16 我的名字是小明,我今年12岁了。17 hello world 我的名字是小明,我今年12岁了,hello!18 """

View Code

固定宽度

format()可以指定输出宽度为多少,当字符串长度少于设定值的时候,默认用空格填充:

ContractedBlock.gif

ExpandedBlockStart.gif

1 data = [{'name': 'Mary', 'college': 'Tsinghua University'},2 {'name': 'Micheal', 'college': 'Harvard University'},3 {'name': 'James', 'college': 'Massachusetts Institute of Technology'}]4 #固定宽度输出

5 for item indata:6 print('{:10}{:40}'.format(item['name'], item['college']))7

8 """输出结果9 Mary Tsinghua University10 Micheal Harvard University11 James Massachusetts Institute of Technology

View Code

当然除了空格,我们也可以选择其他字符来填充,譬如我想打印一条分割线,便可以选择通过-来填充:

ContractedBlock.gif

ExpandedBlockStart.gif

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

5 #固定宽度输出

6 for item indata:7 #每输出一条记录之前打印一条分割线

8 #选择用其他字符来填充时需要指定对齐方式

9 print('{:-^60}'.format('我是分割线'))10 print('{:10}{:40}'.format(item['name'], item['college']))11

12 """输出结果13 ---------------------------我是分割线----------------------------14 Mary Tsinghua University15 ---------------------------我是分割线----------------------------16 Micheal Harvard University17 ---------------------------我是分割线----------------------------18 James Massachusetts Institute of Technology19 """

View Code

对齐方式

format()支持左对齐,右对齐,居中,分别对应<,>,^,具体怎么使用我们看实例:

ContractedBlock.gif

ExpandedBlockStart.gif

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

5

6 print('{:-^50}'.format('居中'))7 for item indata:8 print('{:^10}{:^40}'.format(item['name'], item['college']))9

10 print('{:-^50}'.format('左对齐'))11 for item indata:12 print('{:<10}{:<40}'.format(item['name'], item['college']))13

14 print('{:-^50}'.format('右对齐'))15 for item indata:16 print('{:>10}{:>40}'.format(item['name'], item['college']))17

18 """输出结果19 ------------------------居中------------------------20 Mary Tsinghua University21 Micheal Harvard University22 James Massachusetts Institute of Technology23 -----------------------左对齐------------------------24 Mary Tsinghua University25 Micheal Harvard University26 James Massachusetts Institute of Technology27 -----------------------右对齐------------------------28 Mary Tsinghua University29 Micheal Harvard University30 James Massachusetts Institute of Technology31 """

View Code

数字格式化

常用的示例如下:

ContractedBlock.gif

ExpandedBlockStart.gif

1 #取小数点后两位

2 num = 3.1415926

3 print('小数点后两位:{:.2f}'.format(num))4

5 #带+/-输出

6 num = -3.1415926

7 print('带正/负符号:{:+.2f}'.format(num))8

9 #转为百分比

10 num = 0.34534

11 print('百分比:{:.2%}'.format(num))12

13 #科学计数法

14 num = 12305800000

15 print('科学计数法:{:.2e}'.format(num))16

17 #,分隔

18 num = 12305800000

19 print('","分隔:{:,}'.format(num))20

21 #转为二进制

22 num = 15

23 print('二进制:{:b}'.format(num))24

25 #十六进制

26 num = 15

27 print('十六进制:{:x}'.format(num))28

29 #八进制

30 num = 15

31 print('八进制:{:o}'.format(num))32

33 """输出结果34 小数点后两位:3.1435 带正/负符号:-3.1436 百分比:34.53%37 科学计数法:1.23e+1038 ","分隔:12,305,800,00039 二进制:111140 十六进制:f41 八进制:1742 """

View Code

可以设置参数

ContractedBlock.gif

ExpandedBlockStart.gif

1 print("网站名:{name}, 地址 {url}".format(name="博客园", url="https://home.cnblogs.com/u/yaner2018/"))2

3 #通过字典设置参数

4 site = {"name": "博客园", "url": "www.runoob.com"}5 print("网站名:{name}, 地址 {url}".format(**site))6

7 #通过列表索引设置参数

8 my_list = ['博客园', 'https://home.cnblogs.com/u/yaner2018/']9 print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) #"0" 是必须的

10

11 '''

12 网站名:博客园, 地址 https://home.cnblogs.com/u/yaner2018/13 网站名:博客园, 地址 https://home.cnblogs.com/u/yaner2018/14 网站名:博客园, 地址 https://home.cnblogs.com/u/yaner2018/15 '''

View Code

可以向 str.format() 传入对象:

ContractedBlock.gif

ExpandedBlockStart.gif

1 classdemo(object):2 def __init__(self, value):3 self.value =value4 my_value = demo(6)5 print('value 为: {0.value}'.format(my_value)) #"0" 是可选的

View Code

-----------------------------------------总结-----------------------------------------------------

^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

+ 表示在正数前显示 +,负数前显示 -;(空格)表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

------------------------------------------------------------------------------------------------

此外我们可以使用大括号 {} 来转义大括号,如下实例:

print("{} 对应的位置是 {{0}}".format("runoob"))

#输出:

#runoob 对应的位置是 {0}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值