Skip to content Skip to sidebar Skip to footer

Building Up A String Using A List Of Values

I want to fill in a string with a specific format in mind. When I have a single value, it's easy to build it: >>> x = 'there are {} {} on the table.'.format('3', 'books')

Solution 1:

Use a str.join() call with a list comprehension to build up the objects part:

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

then interpolate that into the full 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'

You could use a generator expression, but for a str.join() call a list comprehension happens to be faster.


Post a Comment for "Building Up A String Using A List Of Values"