-1

I am implementing a linked list in Python 3. I am trying to get output such as "1 2 3" with two spaces in between. My current code prints out "1 2 3 " instead:

  def __str__ (self):
    current = self.first
    if (current == None):
      return None
    while (current.next != None):
      for i in range(1,10):
        if current != None or current != '':
          print(current.data,'  ',end='')
          current = current.next

How do I get rid of the last two spaces?

alexbt
  • 16,415
  • 6
  • 78
  • 87
frank lowe
  • 19
  • 2
  • 7
  • `current.rstrip(' ')` should remove trailing spaces. – Huey Apr 12 '15 at 03:26
  • 2
    What's `for i in range(1,10):` doing here? – Ozgur Vatansever Apr 12 '15 at 03:27
  • 1
    Note that `print()` inserts a single space. between the things it prints, by default. In this case, you're printing two things, `current.data`, and `' '`. Not only will `rstrip()` not help here, as the extra spaces have already been printed, there will be THREE spaces after each item. – Blacklight Shining Apr 12 '15 at 04:00

2 Answers2

2

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.

Community
  • 1
  • 1
Air
  • 8,274
  • 2
  • 53
  • 88
  • The iterable passed to `str.join()` must yield strings, too: `return ' '.join(str(item) for item in self)` – Blacklight Shining Apr 12 '15 at 15:01
  • @BlacklightShining Good catch. I neglected to test whether `join` would implicitly use the `__str__` of the iterable's elements. – Air Apr 12 '15 at 15:47
0

Just a blind guess:

def __str__ (self):
    current = self.first
    def get_data():
        current = current.next
        return current.data
    return " ".join([self.first.data] + list(iter(get_data,None)))

Would you mind sharing your linked list implementation?

L3viathan
  • 26,748
  • 2
  • 58
  • 81