pythonobjectformat

format names from a list of objects into a string


I'm trying to insert the names from a list of objects into a string, but I have a hard time comprehending list comprehension before I can come up with a way to add a spacer between them.

"need {}".format(i.name for i in lst))

what's the right way to do it?


Solution

  • You need to use .join to add the space between the list's elements, then use .format:

    "need {}".format(', '.join(i.name for i in lst))