两者都是格式化字符串用的,前者是比较老的版本,现在已经不推荐,后者更强大一些

%

In [22]: print '%s' % 'hello world'
hello world In [23]: print '%s: %d' % ('name', 13)
name: 13 In [24]: import math In [25]: print 'PI: %.5f' % pi
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-25-b457c33a3305> in <module>()
----> 1 print 'PI: %.5f' % pi NameError: name 'pi' is not defined In [26]: print 'PI: %.5f' % math.pi
PI: 3.14159 In [27]: a = ('Bill', 'Gates') In [28]: '%s, %s' % a
Out[28]: 'Bill, Gates'

  

format

Help on method_descriptor:

format(...)
S.format(*args, **kwargs) -> string Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
(END)

用法如下:

In [29]: "{}".format('hello')
Out[29]: 'hello' In [30]: '{} {}'.format('hello', 'world')
Out[30]: 'hello world' In [31]: '{1} {0} {0}'.format('hello', 'python')
Out[31]: 'python hello hello' In [32]: '{0} {0} {1}'.format(*('hello', 'Python'))
Out[32]: 'hello hello Python' In [33]: '{length} {width}'.format(length=12, width=13)
Out[33]: '12 13' In [34]: '{length} {width}'.format(width=12, length=13)
Out[34]: '13 12' In [35]: '{length} {width}'.format({'width': 12, 'length': 13})
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-35-f8990d240643> in <module>()
----> 1 '{length} {width}'.format({'width': 12, 'length': 13}) KeyError: 'length' In [36]: '{length} {width}'.format(**{'width': 12, 'length': 13})
Out[36]: '13 12' In [37]: "'x': {0[0]}, 'y': {0[1]}".format((12, 13))
Out[37]: "'x': 12, 'y': 13"

最常用的可能就是上面这些,不过format不仅仅如此,还可以做前分位符,指定字符串宽度,代替%s %r,处理时间的格式等

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2" >>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********' >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000' >>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010' >>> '{:,}'.format(1234567890)
'1,234,567,890' >>> points = 19.5
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 88.64%' >>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

大家可以看看官方文档(以上部分例子摘自官方文档):

https://docs.python.org/2/library/string.html

注意:大括号和变量名之间是不能有空格的,否则会提示错误keyerror,如下

In [1]: print '{name}'.format(name='wang')
wang In [2]: print '{ name }'.format(name='wang')
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-2-7b45246725e0> in <module>()
----> 1 print '{ name }'.format(name='wang') KeyError: ' name ' In [3]: print '{ name }'.format(name='wang')

  

  

最新文章

  1. Form Builder的三种查询方法构建
  2. P1965 转圈游戏
  3. JLINK仿真器与ST-LINK仿真器的安装与配置.pdf
  4. openldap安装配置
  5. Windows Phone零距离开发(Composite Thread组合线程)
  6. EasyUI datagrid frozencolumn的bug???
  7. HDOJ 3486 Interviewe
  8. Windows字符集的统一与转换
  9. QT中使用 slot 传递 opencv 中得Mat对象以及 使用多线程集成开源代码。
  10. 用AjaxPro实现二级联动
  11. 全文索引--自定义chinese_lexer词典
  12. UESTC_温泉旅店 CDOJ 878
  13. EasyUI DataGrid编辑单元格时使用combogrid
  14. sql查询语句优化需要注意的几点
  15. MyBatis-执行插入语句的时候返回主键ID到传入的参数对象中
  16. [USACO13DEC]假期计划(黄金)Vacation Planning (gold)
  17. “百度杯”CTF比赛 2017 二月场 爆破-3
  18. 优先队列重载&lt;运算符
  19. pytorch基础
  20. Android的网络通信机制

热门文章

  1. c++ this *this
  2. opencv6.1-imgproc图像处理模块之平滑与形态学操作
  3. Nodejs基础:路径处理模块path总结
  4. jQuery jsonp无法捕获404、500状态错误
  5. matlab画图形函数 semilogx
  6. Socket,TCP/IP,UDP,HTTP,FTP
  7. SharedPreference写入-读取
  8. ScrollView中嵌套ListView显示
  9. WEB界面onload前的加载流程❤❤
  10. 使用CXF 来发布一个 service