【问题标题】:Python: Print using ascii codesPython:使用 ascii 代码打印
【发布时间】:2013-10-07 03:28:12
【问题描述】:

我是 python 的初学者,我在这个程序中遇到了问题:

首先是 NodeList:

class Node:
    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

我的问题出在这个程序中:(打印)

from NodeList import Node

class StackLL:

    def __init__(self):
        self.head = None

    def pushSLL(self,item):
        temp = Node(str(item))
        temp.setNext(self.head)
        self.head = temp
        node = self.head
        print(chr(0x2510)+(chr(0x0000)*(len(item)))+chr(0x250c))
        while node!=None:
            stackeditem = chr(0x2502)+node.data+chr(0x2502)
            print(stackeditem)
            node = node.next   
        print(chr(0x2514)+(chr(0x2500)*(len(item)-1))+chr(0x2518))

每次我打印时,线条似乎都消失了。我尝试使用 len() 只是为了使其准确,但每次该项目添加更多字符时,它都会再次关闭。任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 从您的图片看来,无论您使用什么 GUI,都使用 proportional font。您将很难通过添加空格来调整字符串的宽度。使用等宽字体。

标签: python python-3.x ascii


【解决方案1】:

在 IDLE 设置中使用等宽字体就可以了。

【讨论】:

    【解决方案2】:

    @Kable 回答时使用等宽字体。

    除此之外,最后一个print print 1 less chr(0x2500)

    其他一些注意事项:

    • 使用\u2502 而不是chr(0x2502)
    • 将转储功能与 pushSLL 分开。
    • 第一个和最后一个打印只考虑当前节点的长度。它应该计算所有节点的最大长度。

    class StackLL:
    
        def __init__(self):
            self.head = None
    
        def pushSLL(self, item):
            temp = Node(str(item))
            temp.setNext(self.head)
            self.head = temp
    
        def dump(self):
            length = max(len(node.data) for node in self.allNodes()) if self.head else 0
            print('\u2510{}\u250c'.format(' '*length))
            for node in self.allNodes():
                print('\u2502{:<{}}\u2502'.format(node.data, length))
            print('\u2514{}\u2518'.format('\u2500'*length))
    
        def allNodes(self):
            node = self.head
            while node is not None:
                yield node
                node = node.next
    
    s = StackLL()
    s.pushSLL('Arc')
    s.pushSLL('Circle')
    s.pushSLL('Rect')
    s.dump()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-15
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      相关资源
      最近更新 更多