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

%

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')

  

  

python中%和format的更多相关文章

  1. Python中格式化format()方法详解

    Python中格式化format()方法详解 Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法; Python是完全面向对象的语言, 任何东西都是对象; 字符串的参 ...

  2. Python中的format()函数

    普通格式化方法 (%s%d)生成格式化的字符串,其中s是一个格式化字符串,d是一个十进制数; 格式化字符串包含两部分:普通的字符和转换说明符(见下表), 将使用元组或映射中元素的字符串来替换转换说明符 ...

  3. Python中的format函数

    format是python2.6新增的一个格式化字符串的方法,相对于老版的%格式方法,它有很多优点. 1.不需要理会数据类型的问题,在%方法中%s只能替代字符串类型 2.单个参数可以多次输出,参数顺序 ...

  4. Python中print/format字符串格式化实例

    Python 字符串格式化使用 "字符 %格式1 %格式2 字符"%(变量1,变量2),%格式表示接受变量的类型.简单的使用例子如下 # 例:字符串格式化Name = '17jo' ...

  5. python中的format

    format()格式化字符串,将占位符替换成内容,举个例子: 1 a = "hello {0} welcome to {1}" 2 a1 = a.format("dlrb ...

  6. python 中str format 格式化数字补0方法

      >>> "{0:03d}".format(1)'001'>>> "{0:03d}".format(10)'010'> ...

  7. Python中str.format()字典及list传入详解

  8. python开发_python中str.format()

    格式化一个字符串的输出结果,我们在很多地方都可以看到,如:c/c++中都有见过 下面看看python中的字符串格式函数str.format(): 1 #使用str.format()函数 2 3 #使用 ...

  9. python中的printf:%号拼接字符串和format函数

    在C语言中,我们使用printf("%s","hello")这种形式进行字符串的拼接 在python中,进行这样的拼接有两种实现方式,分别是%号拼接以及使用fo ...

随机推荐

  1. RMQ(ST算法)

    RMQ(Range Minimum/Maximum Query),即区间最值查询,是指这样一个问题:对于长度为n的数列a,回答若干询问RMQ(A,i,j)(i, j<=n),返回数列a中下标在i ...

  2. TM4C123G红外触摸屏:开发板好不容易实现了原理,放到专家设计的板子上无法运行,于是专家跑路项目黄了

    使用TI的TM4C123G LaunchPad开发板,USB接口,来对同样的芯片进行烧写. 我们只用烧写那一块功能,不用另外一个芯片的开发功能,需要跳线   源码项目:   从官方网站TM4C123G ...

  3. 怎样修改 Openstack Horizon(Dashboard)的显示界面 (二)

    上一篇文章介绍了 Dashboard 的基本结构框架,那接下来的问题就是如何在这个框架中加入我们自己想要的内容了.在真正动手之前,让我们先来看看官方的页面是怎么做出来的.首先我们进入 /usr/sha ...

  4. 自己画WinForm 皮肤包括默认控件

    好久没来博客园,今天捣鼓到现在就是为了把之前的皮肤控件完善好, 之前也看了很多技术文章,大多数都是自己重写系统控件实现换肤,几乎没有像东日的(IrisSkin)控件一样 添加一个组件 把系统的皮肤全换 ...

  5. T-SQL 查询、修改数据表

    T-SQL修改表数据 INSERT语句 语法: INSERT [TOP(expression) [PERCENT]] [INTO] { <object> | rowset_function ...

  6. Linux之我见

    Linux哲学之美 linux就像是一个哲学的最佳实践.如果非要对它评价,我真的不知道该怎么赞叹,我只能自豪的说着:“linux的美丽简直让人沉醉.” 我只能说是我处在linux学习的修炼之路上的一个 ...

  7. 42-stat 显示文件的信息

    显示文件的信息 stat [options] [file-list] 参数 file-list指定stat所显示的一个或多个文件的路径名 选项 -f                     显示文件系 ...

  8. webpack入坑之旅(六)配合vue-router实现SPA

    这是一系列文章,此系列所有的练习都存在了我的github仓库中vue-webpack,在本人有了新的理解与认识之后,会对文章有不定时的更正与更新.下面是目前完成的列表: webpack入坑之旅(一)不 ...

  9. quartz介绍

    Quartz 是一个开源的作业调度框架,它完全由 Java 写成,并设计用于 J2SE 和 J2EE 应用中.它提供了巨大的灵活性而不牺牲简单性.你能够用它来为执行一个作业而创建简单的或复杂的调度.本 ...

  10. C# web 获取服务端cookie

    CookieContainer cookies = new CookieContainer();            string url = "http://120.24.56.48:8 ...