Devone Devone - 4 months ago 10
Python Question

How to put generator expressions as input to Python's join method?

How do I put several generator expressions as input to Python's

join
method? I tried the following which don't work. Is there a difference when using Python 2.x and 3.x? My exact version is Python 2.7.12.

def productList(self, obj):
return ", ".join([w.name for w in obj.someProducts.all()],[w.code
for w in obj.someProducts.all()])


and without the
[]


def productList(self, obj):
return ", ".join(w.name for w in obj.someProducts.all(),w.code
for w in obj.someProducts.all())


input:

Product table
Name: Char;
Code: Char;


output:

name1code1, name2code2

Answer

If you want to display name and code, you just need to combine them, you don't need two generators.

', '.join(w.name + ':' + w.code for w in obj.someProducts.all())

Or string formatting:

', '.join('{name}: {code}'.format(name=w.name, code=w.code) for w in obj.someProducts.all())

Or another join (not recommended)

', '.join(':'.join([w.name, w.code]) for w in obj.someProducts.all())

On a side note, Python 3.6 introduces Literal String Interpolation, which means you should be able to do something like this (I'll test this at home, since I don't have 3.6 at work; could someone verify this actually works. Let me know if it doesn't, I'll remove it):

', '.join(f'{w.name}: {w.code}' for w in obj.someProducts.all())