In Python you would typically use str.join()
to build a string from a collection of items with some constant separator. This takes care of the problem of having an extra separator at one or the other end of your string.
But you need to give str.join()
an iterable. Judging by what you've shown of your code, you should be able to make this class iterable by defining the __iter__
method as something like:
def __iter__(self):
current = self.first
while current is not None:
yield current
current = current.next
For more details about the yield
keyword and iterables, I recommend reading What does the "yield" keyword do in Python?.
Note also that PEP 8 recommends using is not None
rather than != None
:
Comparisons to singletons like None
should always be done with is
or
is not
, never the equality operators
Once the linked list is iterable, your string representation is as easy as:
def __str__(self):
return ' '.join(str(o) for o in self) # two spaces between each item
Keep in mind when writing __str__
methods that you should return a string object, not print one in the body of the method.