4

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')
>>> 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 construct the sentence in the exact same way:

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

How would I be able to do that, given that I don't know the length of the list? Using format I could easily construct the string, but then I have to know the length of the list beforehand.

Clement Attlee
  • 723
  • 3
  • 8
  • 16

1 Answers1

6

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.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Martijn, why a list comprehension and not a generator expressions as the parameter to `str.join`? – Robᵩ Nov 12 '15 at 20:55
  • @Robᵩ Because `join` will convert the generator expression to list by itself.And by passing the generator expression to join you will force the `join` to does this job! – Mazdak Nov 12 '15 at 20:55
  • @Robᵩ: I always am asked this, and I always edit in the link to Raymond's exposé as to how it is faster to use a list comp. – Martijn Pieters Nov 12 '15 at 20:58