Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6908142
  • 博文数量: 3857
  • 博客积分: 6409
  • 博客等级: 准将
  • 技术积分: 15948
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-02 16:48
个人简介

迷彩 潜伏 隐蔽 伪装

文章分类

全部博文(3857)

文章存档

2017年(5)

2016年(63)

2015年(927)

2014年(677)

2013年(807)

2012年(1241)

2011年(67)

2010年(7)

2009年(36)

2008年(28)

分类: Python/Ruby

2014-04-02 10:58:27

原文地址:python字符串的格式化 作者:dba_life

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



阅读(427) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~