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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Martijn, why a list comprehension and not a generator expressions as the parameter to str.join?
@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!
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.