Python 序列类型拆包 %s 和'{}'.format 的功能差异之一

>>> 1, 2, 3 #这样写成一行相当于一个元组
(1, 2, 3)
>>> x = 1, 2, 3
>>> x
(1, 2, 3)
>>> type(x)
<class 'tuple'>
>>> x, y, z = 4, 6, 5
>>> x, y, z
(4, 6, 5)
>>> tx = x, y, z
>>> tx
(4, 6, 5)
>>> a, b, c = tx
>>> a
4
>>> b
6
>>> c
5
>>> (1, 3, 5)
(1, 3, 5)
>>>

>>> li = [('张三', 50), ('李四', 30)]
>>> for name,_ in li:
... print(name)
... print(_)
...
张三
50
李四
30

>>> for inf in li:
... print('%s__%s' % inf)  #这个功能只有%s 能做到, '{}'.format()做就会出错
...
张三__50
李四__30
>>> for inf in li:
... print('{}, {}'.format(inf))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: tuple index out of range
>>> for inf in li:
... print('{}, {}'.format inf)
File "<stdin>", line 2
print('{}, {}'.format inf)
^
SyntaxError: invalid syntax

>>> for inf in li:
... print('{}, {}'.format(*inf)) # 如果用*拆包, 就可以了
...
张三, 50
李四, 30

'%s'无法拆字符串的包,  但是'{}'.format()却可以:

>>> st = 'abcd'
>>> *st
File "<stdin>", line 1
SyntaxError: can't use starred expression here
>>> s, *a = st
>>> a
['b', 'c', 'd']
>>> s
'a'
>>> print('%s %s %s %s' % st)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

>>> print('%s %s %s %s' % (st))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

>>> print('%s %s %s %s' %(*st))
File "<stdin>", line 1
SyntaxError: can't use starred expression here


>>> print('{}'.format(*st))
a
>>> print('{2}'.format(*st))
c
>>>

>>> l = (4, 5)
>>> def jia(x, y):
... return x+y
...
>>> jia(*l)
9
>>>

原文地址:https://www.cnblogs.com/guiyuhua/p/8631529.html