2012-04-01 62 views
0

不知何故,换行符不能正常工作。 这是我得到:Linebreak不能正常工作 - Python

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' 

这是在函数中使用的代码。 重要的部分应该是STR和showRecentComments功能

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 

问候,纳尔逊·格雷戈里奥

+0

“这就是我得到的结果:”呃,你会怎么做? – 2012-04-01 23:15:16

+0

你不应该从'__str__'返回'None',而是返回''''。 – 2012-04-02 04:47:25

回答

2

看起来你正在寻找的字符串表示,它会显示你换行字符作为\n。如果你print或写入例如标准输出(sys.stdout.write(s))代替字符串,换行符将被展开。

+0

虽然__str__函数工作。 应该showRecentComments做同样的事情吗? ----- 确实打印而不是退货。 我想它会做。 – 2012-04-01 23:29:49

+0

'return'仍然有意义,但是你想'打印'返回的字符串。例如如果'c'作为'Comments'类的一个实例,则可以执行'print c',它将使用'__str__'来获取所述实例的字符串表示并将其打印出来。 – zigg 2012-04-01 23:37:17