format()函数

相对基本格式化输出采用‘% ’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘% ’。
(1)通过位置替换
[python]  view plain  copy
  1. >>> print '{0} {1}'.format('hello','world')  
  2. hello world  
  3. >>> print '{} {}'.format('hello','world')  
  4. hello world  
  5. >>> print '{0} {1} {0}'.format('hello','world')  
  6. hello world hello  
在字符串模板中确定位置,并且位置可以不按顺序,format()可传入任意数目的参数。
(2)关键字替换
也可以采用关键字替换的方法。
[python]  view plain  copy
  1. >>> print 'i love {python}'.format(python='you')  
  2. i love you  
(3)其他使用方法如:
可以指定输出长度和输出的对齐方式,其中对齐方式有一下几种:
< (默认)左对齐
> 右对齐
^ 中间对齐
= (只用于数字)在小数点后进行补齐
[python]  view plain  copy
  1. >>> print format('string','2s')  
  2. string  
  3. >>> print format(3.14151617,'.5f')  
  4. 3.14152  
  5. >>> print '{0:>10}'.format('sqxu')    #10个占位符,右对齐  
  6.       sqxu  
  7. >>> print '{0:4.2f}'.format(3.141516)  
  8. 3.14  
  9. >>> print '{0:6.2f}'.format(3.141516)  
  10.   3.14  
  11. >>> print '{0:>6.2f}'.format(3.141516)  
  12.   3.14  
  13. >>> print '{1:<10},{0:<15}'.format('sqxu','USTC')  
  14. USTC      ,sqxu             
  15. >>> print 'name={name},age={age}'.format(name='sqxu',age=25)  
  16. name=sqxu,age=25  
同上述格式化输出一样,也可以通过格式化指示符来控制格式。
例如,浮点数可以被格式化为一般格式或用幂来表示。
'b' - 二进制。将数字以2为基数进行输出。
'c' - 字符。在打印之前将整数转换成对应的Unicode字符串。
'd' - 十进制整数。将数字以10为基数进行输出。
'o' - 八进制。将数字以8为基数进行输出。
'x' - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
'e' - 幂符号。用科学计数法打印数字。用'e'表示幂。
'g' - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
'n' - 数字。当值为整数时和'd'相同,值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符。
'%' - 百分数。将数值乘以100然后以fixed-point('f')格式打印,值后面会有一个百分号。
[python]  view plain  copy
  1. >>> print '{0:b}'.format(3)  
  2. 11  
  3. >>> print '{0:c}'.format(30)  
  4.   
  5. >>> print '{0:d}'.format(3)  
  6. 3  
  7. >>> print '{0:o}'.format(10)  
  8. 12  
  9. >>> print '{0:x}'.format(30)  
  10. 1e  
  11. >>> print '{0:e}'.format(3)  
  12. 3.000000e+00  
  13. >>> print '{0:f}'.format(3)  
  14. 3.000000  
  15. >>> print '{0:g}'.format(3)  
  16. 3  
  17. >>> print '{0:n}'.format(3)  
  18. 3  
  19. >>> print '{0:n}'.format(3.1415)  
  20. 3.1415  
  21. >>> print '{0:%}'.format(3.15)  
  22. 315.000000%  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值