使用值列表构建字符串

时间:2015-11-12 20:46:38

标签: 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'},...]

我想以完全相同的方式构建句子:

There are 3 books and 1 pen and 2 cellphones and... on the table

考虑到我不知道列表的长度,我怎么能做到这一点?使用format我可以很容易地构造字符串,但是我必须事先知道列表的长度。

1 个答案:

答案 0 :(得分:6)

使用str.join() calllist comprehension * 来构建对象部分:

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

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

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

演示:

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

* 可以使用generator expression,但str.join()来电a list comprehension happens to be faster