我想填写一个特定格式的字符串。当我有一个单一的价值时,很容易建立它:
>>> 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
我可以很容易地构造字符串,但是我必须事先知道列表的长度。
答案 0 :(得分:6)
使用str.join()
call和list 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。