Search code examples
pythonlistlinked-listline-breaks

Linebreak not working - Python


Somehow the linebreaks are not working as they should. This is what I get:

Expected:
    O meu u2 2 post
    http://www.yahoo.com
    1 Gosto, 0 Nao gosto
    <BLANKLINE>
    O meu u2 post
    http://www.altavista.com
    1 Gosto, 0 Nao gosto
Got:
    'O meu u2 2 post\nhttp://www.yahoo.com\n1 Gosto, 0 Nao Gosto\n\nO meu u2\nhttp://www.yahoo.com\n1 Gosto, 0 Nao Gosto'

This is the code used in the function. The important parts should be the str and showRecentComments functions

class Comments():
def __init__(self, u=None, text='', link=None):
    self.u = u
    self.text = text
    self.link = link
    self.topo = None
    self.fim = None

def __str__(self):
    actual = self.topo
    s = ''
    if actual == None:
        return None
    while actual != None:
        if actual.seg == None:
            s += str(actual)
            actual = actual.seg
        else:
            s += str(actual) + '\n' + '\n'
            actual = actual.seg
    return s

def add(self,comment):
    if self.topo == None:
        self.topo = comment
        self.fim = comment
    else:
        comment.seg = self.topo
        self.topo.ant = comment
        self.topo = comment

def remove(self,comment):
    actual = self.topo
    if (self.topo == self.fim) and (self.topo == comment):
        self.topo = None
        self.fim = None
    while actual!=None:
        if actual == comment:
            if self.topo==comment:
                actual.seg.ant = None
                self.topo = actual.seg
            elif self.fim==comment:
                actual.ant.seg = None
                self.fim = actual.ant
            else:
                actual.seg.ant = actual.ant
                actual.ant.seg = actual.seg
            break
        else:
            actual = actual.seg

def countLike(self):
    count = 0
    actual = self.topo
    while actual != None:
        if len(actual.likeList) >= 1:
            count += 1
            actual = actual.seg
        else:
            actual = actual.seg
    return count

def showRecentComments(self,n):
    count = 1
    actual = self.topo
    sC = ''
    if actual == None:
        return None
    while actual != None:
        if count < n:
            sC += str(actual) + '\n' + '\n'
            count += 1
            actual = actual.seg
        elif count == n:
            sC += str(actual)
            count += 1
            actual = actual.seg
        elif count > n:
            break 
    return sC

Regards, Nelson Gregório


Solution

  • It looks like you're looking at the representation of the string, which will show you the newline characters as \n. If you print or write to e.g. stdout (sys.stdout.write(s)) the string instead, the newlines will be expanded.