Python 使用值列表构建字符串

Python 使用值列表构建字符串,python,string,python-3.x,Python,String,Python 3.x,我想用特定的格式填充字符串。当我有一个单一的价值观时,很容易构建它: >>> x = "there are {} {} on the table.".format('3', 'books') >>> x 'there are 3 books on the table.' 但是如果我有一长串的对象呢 items =[{'num':3, 'obj':'books'}, {'num':1, 'obj':'pen'},...] 我想用完全相同的方式来构造这个句子:

我想用特定的格式填充字符串。当我有一个单一的价值观时,很容易构建它:

>>> x = "there are {} {} on the table.".format('3', 'books')
>>> x
'there are 3 books on the table.'
但是如果我有一长串的对象呢

items =[{'num':3, 'obj':'books'}, {'num':1, 'obj':'pen'},...]
我想用完全相同的方式来构造这个句子:

There are 3 books and 1 pen and 2 cellphones and... on the table
既然我不知道名单的长度,我怎么能做到这一点呢?使用
格式
我可以很容易地构造字符串,但是我必须事先知道列表的长度。

使用a和a*来构建对象部分:

objects = ' and '.join(['{num} {obj}'.format(**item) for item in items])
然后在整句话中插入:

x = "There are {} on the table".format(objects)
演示:



*您可以使用,但对于
str.join()
调用。

Martijn,为什么要使用列表理解而不是生成器表达式作为
str.join
的参数?@Robᵩ 因为
join
将自动将生成器表达式转换为list。通过将生成器表达式传递到join,您将强制
join
执行此操作@抢劫ᵩ: 我总是被问到这个问题,我总是在雷蒙德的展览的链接中编辑如何更快地使用列表。
>>> items = [{'num': 3, 'obj': 'books'}, {'num': 1, 'obj': 'pen'}, {'num': 2, 'obj': 'cellphones'}]
>>> objects = ' and '.join(['{num} {obj}'.format(**item) for item in items])
>>> "There are {} on the table".format(objects)
'There are 3 books and 1 pen and 2 cellphones on the table'