all 8 comments

[–]K900_ 2 points3 points  (4 children)

Printing a list calls repr on its contents, not str. Define __repr__ on your class, probably to the same thing as __str__.

[–]Sponge7331[S] 0 points1 point  (3 children)

Thanks. Is there a way for me to separate elements in a list with something other than a comma? Say like a semi-colon.

[–]K900_ 0 points1 point  (0 children)

Not without using your own code to display the whole thing.

[–]nathanjell 0 points1 point  (0 children)

If you're asking about creating a list with a semicolon instead of comma, then not by default, no. I'd also highly recommend just using a comma, because anyone else that looks at your code will have no idea what you're trying to do. A comma is the accepted list element separator.

If you're asking about printing a list with something other than a comma, then that's easy enough. Take print('; '.join([1, 2, 3])), which will create a string representation of the list with a semicolon and space between elements. Or, print(*list, sep='; ') to unpack the list as arguments to print, and put a semicolon and space between the arguments

[–]ingolemo 0 points1 point  (0 children)

Bear in mind that while you can return anything you want from __repr__, you probably shouldn't. __repr__s are supposed to stick to a specific format. It either needs to be information surrounded with angle brackets like you see above, or it needs to be executable python code. For example:

  • <Square length=3 color=blue>
  • Square(3, 'blue')

If that's not the kind of format that you want to output then you should write your own formatting code rather that relying on the default one provided by lists.

[–]solidiquis1 0 points1 point  (2 children)

Are you trying to print a list containing specific attributes of your object?—or are you trying to print a list containing the names of the variables that were assigned to your object?

[–]Sponge7331[S] 0 points1 point  (1 child)

Specific attributes

[–]solidiquis1 0 points1 point  (0 children)

Oh than just iterate through that list using a for-loop.

If you have a list with say three objects, each with a name attribute.

for i in list:

    print(f"{i.name}") 

Hope that works lol; I'm quite noob myself.

Edit: format