使用值列表构建字符串

Cle*_*lee 4 python string python-3.x

我想填写一个特定格式的字符串.当我有一个值时,很容易构建它:

>>> x = "there are {} {} on the table.".format('3', 'books')
>>> x
'there are 3 books on the table.'
Run Code Online (Sandbox Code Playgroud)

但是如果我有很长的对象列表呢?

items =[{'num':3, 'obj':'books'}, {'num':1, 'obj':'pen'},...]
Run Code Online (Sandbox Code Playgroud)

我想用完全相同的方式构造句子:

There are 3 books and 1 pen and 2 cellphones and... on the table
Run Code Online (Sandbox Code Playgroud)

鉴于我不知道列表的长度,我怎么能这样做呢?使用format我可以很容易地构造字符串,但我必须事先知道列表的长度.

Mar*_*ers 6

使用带有列表推导*str.join()调用来构建对象部分:

objects = ' and '.join(['{num} {obj}'.format(**item) for item in items])
Run Code Online (Sandbox Code Playgroud)

然后将其插入到完整的句子中:

x = "There are {} on the table".format(objects)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

*可以使用生成器表达式,但对于str.join()调用,列表理解恰好更快.