4

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.

1
  • Here is a way just using joins: '\n'.join(['|'.join([o.name, str(o.age)]) for o in obj_list]) Commented Apr 6, 2017 at 11:39

1 Answer 1

8

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)).

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

6 Comments

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?
what do you mean by second best way?
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
Felix, when i use your code from above i get this result TypeError: join() takes exactly one argument (2 given)
got that right now too :) Thank you very much! --> SOLVED
|

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.