Home > Software design >  return each string representation in a list of user-defined objects in a new line
return each string representation in a list of user-defined objects in a new line

Time:09-29

I have a list where each element is a user-defined class, class_object_list. I wish to return each string representation of that list in a new line and the code needs to be wrapped inside an f-string (or would work inside a return statement).

Or basically, put the equivalent of the following code inside a return statment

for i in class_object_list:
    print(i)

i've tried ''.join([str(i) for i in class_object_list]) but it doesnt print each string representation in a new line.

Also tried nl = '\n', f"{nl.join([*class_object_list])}" but it gave a TypeError: sequence item 0: expected str instance error.

And tried print(*class_object_list, sep='\n') but it only works with a print statement

CodePudding user response:

Use:

'\n'.join([str(i) for i in class_object_list])

Or:

'\n'.join(map(str, class_object_list))
  • Related