2

i have an orm based object list. i now want to concatenate some attributes delimited by the "|" (pipe) and then concatenate all objects by using "\n".

i tried:

class A(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

obj_list = [A("James", 42), A("Amy", "23")]
"\n".join("|".join(o.name, o.age for o in obj_list))

File "<console>", line 1
SyntaxError: Generator expression must be parenthesized if not sole Argument

what exactly must be parenthesized?

Any hints?

Tank you.

sfr
  • 43
  • 1
  • 4

1 Answers1

6

I think this is what you wanted to achieve:

obj_list = [A("James", 42), A("Amy", "23")]
"\n".join("|".join((o.name, o.age)) for o in obj_list)

Result:

James|42
Amy|23

Note: if your object contains non-string attributes, you have to convert those to strings, e.g. "|".join(o.name, str(o.age)).

Felix
  • 6,131
  • 4
  • 24
  • 44
  • Thank you. That is - for me - the second best way :) can i use a join and a inner join, so i only have to add arguments if i want to increase them or do i have to add curly braces every time too? – sfr Apr 06 '17 at 11:34
  • what do you mean by second best way? – Felix Apr 06 '17 at 11:35
  • `join` is one of the times when it makes more sense to use a list comprehension in a function call. When you give it a generator expression, it has to iterate through the expression and build a list anyways. [More](http://stackoverflow.com/a/9061024/6779307) – Patrick Haugh Apr 06 '17 at 11:40
  • Felix, when i use your code from above i get this result TypeError: join() takes exactly one argument (2 given) – sfr Apr 06 '17 at 11:45
  • got that right now too :) Thank you very much! --> SOLVED – sfr Apr 06 '17 at 11:47
  • @PatrickHaugh you're right, but since it speed difference isn't that high, I'd say that it doesn't matter in most cases. See http://stackoverflow.com/questions/37782066/list-vs-generator-comprehension-speed-with-join-function?noredirect=1&lq=1 for timing – Felix Apr 06 '17 at 11:50