Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: string join multiple attributes from object

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.

like image 200
sfr Avatar asked Oct 22 '25 06:10

sfr


1 Answers

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

like image 61
Felix Avatar answered Oct 24 '25 19:10

Felix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!