转载自:http://www.cnblogs.com/kaituorensheng/p/5709970.html

python自2.6后,新增了一种格式化字符串函数str.format(),威力十足,可以替换掉原来的%

:以下操作版本是python2.7

映射示例

语法

通过{} 和 :  替换 %

通过位置

>>> '{0} is {1}'.format('jihite', '4 years old')
'jihite is 4 years old'
>>> '{0} is {1} {0}'.format('jihite', '4 years old')
'jihite is 4 years old jihite'

通过format函数可以接受不限参数个数、不限顺序

通过关键字

>>> '{name}:{age}'.format(age=4,name='jihite')
'jihite:4'
>>> '{name}:{age}'.format(age=4,name='jihite',locate='Beijing')
'jihite:4'

format括号内用=给变量赋值

通过对象属性

>>> class Person:
... def __init__(self, name, age):
... self.name,self.age = name, age
... def __func__(self):
... return "This guy is {self.name}, is {self.age} old".format(self=self)
...
>>> s =Person('jihite', 4)
>>> s.__func__()
'This guy is jihite, is 4 old'

通过下标

>>> '{0[0]} is {0[1]} years old!'.format(['jihite', 4])
'jihite is 4 years old!'
>>> '{0} is {1} years old!'.format('jihite', 4)
'jihite is 4 years old!'

其实就是通过位置

格式限定符

通过{} : 符号

填充和对齐

^<>分别表示居中、左对齐、右对齐,后面带宽度

>>> '{:>10}'.format('jihite')
' jihite'
>>> '{:<10}'.format('jihite')
'jihite '
>>> '{:^10}'.format('jihite')
' jihite '

精度和类型f

精度常和f一起使用

>>> '{:.2f}'.format(3.1415)
'3.14'
>>> '{:.4f}'.format(3.1)
'3.1000'

进制转化

>>> '{:b}'.format(10)
'1010'
>>> '{:o}'.format(10)
'12'
>>> '{:d}'.format(10)
'10'
>>> '{:x}'.format(10)
'a'

其中b o d x分别表示二、八、十、十六进制

千位分隔符

>>> '{:,}'.format(1000000)
'1,000,000'

>>> '{:,}'.format(100000.23433)
  '100,000.23433'

>>> '{:,}'.format('abcedef')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Cannot specify ',' with 's'. 尤其是其中的精度与类型,用起来很方便

最新文章

  1. [Angularjs]表单验证
  2. VS2008上借助VA来提示QT API
  3. Git教程之版本回退(4)
  4. log4net项目中如何配置,以下详解
  5. selenium firefox
  6. POJ-3253 Fence Repair---Huffman贪心
  7. day07 Class_field_method_反射
  8. nginx实现Ipv6地址解析
  9. Java网络通信协议、UDP、TCP类加载整理
  10. Spring Boot 构建电商基础秒杀项目 (五) 用户注册
  11. 洛谷1443 马的遍历【bfs】
  12. nginx:支持https
  13. 数据库的ds命令
  14. Xpath同时选取不同属性的元素
  15. iOS使用shell脚本注入混淆内容
  16. 对JVM的理解
  17. 更改文本的编码jsp.xml.java
  18. OkHttp完全解析之整体调用流程
  19. 利用WINDOWS活动目录提供LDAP的方案
  20. 工程web-inf 下文件,路径访问

热门文章

  1. Hive date_add 和 date_diff 函数
  2. java构造器内部多态方法
  3. 数据结构C语言实现
  4. MFC坐标问题
  5. pycharm内对python文件的模板
  6. springCloud的使用06-----分布式配置
  7. How To Release and/or Renew IP Addresses on Windows XP | 2000 | NT
  8. java并发编程之美-阅读记录4
  9. Docker入门 .Net Core 使用Docker全程记录
  10. 西里尔字 俄语 - Cyrillic