有人可以解释以下行为吗?
In [23]: l = ['', 'Camino Cielo', '', '']
In [24]: ll = ['', 'Maricopa', 'Highway', '']
In [26]: ' '.join(e for e in l if e)
Out[26]: 'Camino Cielo'
In [27]: ' '.join(e for e in ll if e)
Out[27]: 'Maricopa Highway'
In [29]: glue = ' '
In [30]: '%s'.join(e for e in ll if e) % glue
Out[30]: 'Maricopa Highway'
In [31]: '%s'.join(e for e in l if e) % glue
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
31-7ea8ccb65d69> in <module>()
----> 1 '%s'.join(e for e in l if e) % glue
TypeError: not all arguments converted during string formatting
答案 0 :(得分:4)
%
运算符应用于str.join()
调用的结果:
>>> '%s'.join(e for e in ll if e)
'Maricopa%sHighway'
>>> '%s'.join(e for e in ll if e) % glue
'Maricopa Highway'
>>> '%s'.join(e for e in l if e)
'Camino Cielo'
请注意,最后一个结果中有 no %s
; e for e in l if e
生成器表达式的输出中只有一个字符串,其余的都是空的,不会通过if e
过滤器。
如果没有占位符,则无法插入glue
:
>>> 'Camino Cielo' % glue
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
如果要加入两个以上的字符串,您也会遇到问题:
>>> '%s'.join(['foo', 'bar', 'spam'])
'foo%sbar%sspam'
>>> '%s'.join(['foo', 'bar', 'spam']) % glue
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
在这种情况下,只需直接使用glue
:
>>> glue.join(e for e in ll if e)
'Maricopa Highway'
>>> glue.join(e for e in l if e)
'Camino Cielo'
>>> glue.join(['foo', 'bar', 'spam'])
'foo bar spam'
当您的所有模板都包含'%s'
时,内插几乎没有用。