如何在不打印/ n的情况下返回字符串,就像打印它一样

时间:2019-07-08 12:36:13

标签: python string printing return-type

我正在做作业,我需要将一棵树作为字符串返回。我已经解决了问题,并且在打印时还可以。问题在于作业要求返回字符串,当我返回时,它会打印/n字符而不将其视为新行。

如果我打印出来,那就是结果:

04  
|
05  
|   
01  
|   
06  
|   
03  

这应该是我必须返回的字符串。

但是如果我使用return代替打印,它将返回以下内容:

04  \n  |   \n  05  \n  |   \n  01  \n  |   \n  06  \n  |   
\n  03

这是我正在使用的课程:

class Albero:

  def __init__(self,V):

     self.id=V
     self.f=[]


  n=Albero("04")
  n1=Albero("05")
  n2=Albero("01")
  n3=Albero("06")
  n4=Albero("03")
  n.f=[n1]
  n1.f=[n2]
  n3.f=[n4]

 def treeLines(node,getInfo):
    nodeId,nodeChildren = getInfo(node)
    subNodes   = [treeLines(child,getInfo) for child in nodeChildren]
    widths     = [ len(childText[0]) for childText in subNodes ]
    totalWidth = sum(widths) + 2*len(widths) - 1
    totalWidth = max(totalWidth,len(nodeId))
    nodeLine   = nodeId.center(totalWidth," ")
    result     = [nodeLine]
    if not nodeChildren: return result
    linksLine   = "  ".join("|".center(width," ") for width in widths)
    linksLine   = linksLine.center(totalWidth," ")
    leftIndent  = linksLine.index("|") + 1
    rightIndent = linksLine[::-1].index("|") + 1
    spanWidth   = totalWidth - leftIndent - rightIndent - 1
    leftSpan    = nodeLine.index(nodeId)-leftIndent+(len(nodeId)-1)//2
    rightSpan   = spanWidth - leftSpan   
    spanLine    = " "*leftIndent + "_"*leftSpan + "|" + "_"*rightSpan + " "*rightIndent
    if len(nodeChildren) > 1 : result.append(spanLine)
    result.append(linksLine)
    maxHeight   = max(len(subNode) for subNode in subNodes)
    subNodes    = [ subNode + [" "*len(subNode[0])]*(maxHeight-len(subNode)) for subNode in subNodes ]
    result     += ["  ".join([subNode[i] for subNode in subNodes]).center(totalWidth," ") for i in range(maxHeight) ]
    return result  

def treeText(node,getInfo): return  "\n".join(treeLines(node,getInfo))

print( treeText(Albero.radice,lambda n:(n.id,n.f)) )

如何返回打印中的字符串格式?

0 个答案:

没有答案