居中对齐 %d 接受 spa 开始 nbsp 字符 /usr
1. 替代旧的%输出
旧的格式化输出方法:
- #!/usr/bin/python
- name = ‘Tom‘
- age = 18
- print ‘%s is %d years old‘ % (name,age)
使用format函数格式化输出:
- #!/usr/bin/python
- name = ‘Tom‘
- age = 18
- print ‘{0} is {1} years old‘.format(name,age)
相比于旧的输出方式,字符串的format函数可以接受不限个参数,位置可以不按顺序,可以不用或者用多次。
2. 可以用来限制小数点位数
例如
- # ! /usr/bin / python#保留小数点后3位,0.333 print‘ {
- 0 : .3f
- }‘.format(1.0 / 3)
3. 填充对齐
- #!/usr/bin/python
- #输出‘__hello___‘,长度为10,长度不足时用‘_‘补足
- #其中‘^‘表示居中对齐,‘<‘左对齐,‘>‘右对齐
- print ‘{0:_^10}‘.format(‘hello‘)
Python字符串format函数
来源: http://www.bubuko.com/infodetail-2283778.html