Creating a String Using a List of Values

I want to fill in a line with a specific format. When I have one value, it's easy to build it:

>>> x = "there are {} {} on the table.".format('3', 'books')
>>> x
'there are 3 books on the table.'

but what if i have a long list of objects

items =[{'num':3, 'obj':'books'}, {'num':1, 'obj':'pen'},...]

and I want to build the sentence in exactly the same way:

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

How can I do this, given that I do not know the length of the list? Using format, I could easily build a string, but then I have to know the length of the list in advance.

+4
source share
1 answer

Use the str.join()call with the concept * to create a part of objects:

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

then interpolate this into a complete sentence:

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

Demo:

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

* , str.join() .

+6

Source: https://habr.com/ru/post/1615649/


All Articles