3-3字符串格式化(p47)

字符串 % 被格式化的值或字符串或者元组

  • %:字符串格式化操作符;%s称为转换说明符

  • 基本的转换说明符:

  • %字符:标记转换说明符的开始

  • 转换标志:- 左对齐;+ 转换值前加上正负号;“”(空白字符) 正数前保留空格;0 若位数不够则用0填充

  • 转换类型

d,i  带符号的十进制整数

o    不带符号的八进制

u    不带符号的十进制

x    不带符号的十六进制(小写)

X    不带符号的十六进制(大写)

e    科学计数法表示的浮点数(小写)

E    科学计数法表示的浮点数(大写)

f,F  十进制浮点数

g    如果指数大于-4或者小于精度值则和e相同,其他情况与f相同

G   如果指数大于-4或者小于精度值则和E相同,其他情况与f相同

C   单字符

r    字符串(使用repr转换任意Python对象)

s    字符串(使用str转换任意Python对象)

例子1:

  • 从math模块中导入pi,格式化pi

 1 #!/usr/bin/env python
 2 #-*- coding:utf-8 -*-
 3 from math import pi
 4 print ('%10f'%pi)
 5 print ('%-10f' % pi)
 6 print ('%010f' % pi)
 7 print ('% -010f' % pi)
 8 print ('%0-10f' % pi)
 9 print ('% 10.2f' % pi)
10 print ('%+10.2f' % pi)
11 print ('%-010.2f' % pi)
12 print ('%10.2f'%pi)
13 print ('%010.2f' % pi)
14 print ('%.2f'%pi)
15 print ('%.*s'%(5,'Guido van Rossum'))
  • 运行结果:

 1   3.141593
 2 3.141593  
 3 003.141593
 4  3.141593 
 5 3.141593  
 6       3.14
 7      +3.14
 8 3.14      
 9       3.14
10 0000003.14
11 3.14
12 Guido
  • 小知识:%前后有无空格皆可。

 例子2:

  • 使用给定的宽度打印格式化后的价格列表

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 width=raw_input("Please enter width: ")
 4 price_width=10
 5 item_width=int(width)-price_width
 6 header_format='%-*s%*s'
 7 format='%-*s%*.2f'
 8 #s=['=']
 9 print '=' * int(width)
10 print header_format % (item_width,'Item',price_width,'Price')
11 print '+' * int(item_width),
12 print '-' * int(price_width)
13 print format % (item_width,'Apples',price_width,0.4)
14 print format % (item_width,'Pears',price_width,0.5)
15 print format % (item_width,'Cantaloupes',price_width,1.92)
16 print format % (item_width,'Dried Apricots(16 0z.)',price_width,8)
17 print format % (item_width,'Pruned(4 lbs',price_width,12)
18 print '=' * int(width)
  • 效果:

 1 Please enter width: 35
 2 ===================================
 3 Item                          Price
 4 +++++++++++++++++++++++++ ----------
 5 Apples                         0.40
 6 Pears                          0.50
 7 Cantaloupes                    1.92
 8 Dried Apricots(16 0z.)         8.00
 9 Pruned(4 lbs                  12.00
10 ===================================
  • 注意:

raw_input()输入的是字符串,需要转换成int()才能与字符串相乘,即:'=' * int(width)

print不换行,只需要在print ()后加个逗号即可,不过他们中间有个好像空格的特殊符号

猜你喜欢

转载自www.cnblogs.com/scholarly/p/10193558.html