Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1360062
  • 博文数量: 243
  • 博客积分: 888
  • 博客等级: 准尉
  • 技术积分: 2955
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-05 14:33
个人简介

漫漫长路,其修远兮!

文章分类

全部博文(243)

文章存档

2017年(2)

2016年(22)

2015年(32)

2014年(57)

2013年(107)

2012年(23)

分类: Python/Ruby

2014-04-01 18:04:32

1.格式化为字符串%s 
>>> format = "Hello, %s. %s enough for ya?"
>>> values = ('world', 'Hot')
>>> print format % values
Hello, world. Hot enough for ya?

2.格式化为实数%f
>>> format = "Pi with three decimals: %.3f"//保留小数点后3个有效数字
>>> from math import pi//导入pi的值
>>> print format % pi
Pi with three decimals: 3.142

转换标志:  -表示左对齐,+表示转换后要加上正负号,“”空白字符表示正数之前保留空格,0表示转换值若位数不够则用0填充
*表示宽度从值元组中读出
.后面跟精度值

'%.*s' %(5,'Guido van Rossum')
'Guido'

>>> pi = 3.1415
>>> '%010.2f' % pi
'0000003.14'
>>> '%-10.2f' % pi
'3.14      '
>>> '%10.2f' % pi
'      3.14'
>>> '% 10.2f' % pi
'      3.14'
>>> '%+10.2f' % pi
'     +3.14'


点击(此处)折叠或打开

  1. width = input('Please enter width: ')

  2. price_width = 10
  3. item_width = width - price_width

  4. header_format = '%-*s%*s'
  5. format = '%-*s%*.2f'

  6. print '=' * width

  7. print header_format % (item_width, 'Item', price_width, 'Price')

  8. print '-' * width

  9. print format % (item_width, 'Apples', price_width, 0.4)
  10. print format % (item_width, 'Pears', price_width, 0.5)
  11. print format % (item_width, 'Cantaloupes', price_width, 1.92)
  12. print format % (item_width, 'Dried Apricots (16 oz.)', price_width, 8)
  13. print format % (item_width, 'Prunes (4 lbs.)', price_width, 12)

点击(此处)折叠或打开

  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 oz.) 8.00
  9. Prunes (4 lbs.) 12.00



阅读(2336) | 评论(0) | 转发(1) |
0

上一篇:python socket编程

下一篇:python读写文件操作

给主人留下些什么吧!~~