如何摆脱使用stdout python3打印列表的尾随空格

问题描述 投票:-2回答:1

我在python中使用stdout打印输出,但它保持打印的内容最后有空白,而rsplit()总是给我一个错误。代码如下。



class Node:
    def __init__(self, d):
        self.data = d
        self.left = None
        self.right = None


# function to convert sorted array to a
# balanced BST
# input : sorted array of integers
# output: root node of balanced BST
def sort_array_to_bst(arr):
    if not arr:
        return None

    # find middle
    mid = (len(arr)) / 2
    mid = int(mid)

    # make the middle element the root
    root = Node(arr[mid])

    # left subtree of root has all
    # values <arr[mid]
    root.left = sort_array_to_bst(arr[:mid])

    # right subtree of root has all
    # values >arr[mid]
    root.right = sort_array_to_bst(arr[mid + 1:])
    return root


# A utility function to print the pre-order
# traversal of the BST
def pre_order(node):
    if not node:
        return
    if root:
        sys.stdout.write(node.data + ' ')
        pre_order(node.left)
        pre_order(node.right)


def no_spaces(s):
    return ' '.join(s.rsplit())


if __name__ == '__main__':
    arr = []
    for line in sys.stdin.readline().strip().split(" "):
        arr.append(line)
    # arr = [7, 898, 157, 397, 57, 178, 26, 679]
    # Output = 178 57 26 157 679 397 898
    narr = arr[1:]
    print(narr)
    narr = sorted(narr, key=int)
    root = sort_array_to_bst(narr)
    pre_order(root)

我输入7 898 157 397 57 178 26 679我得到输出178 57 26 157 679 397 898. .是为了说明空白,但在实际输出中注意它只是一个空白区域。我试过了 sys.stdout.write(node.data + ' ').rsplit()但得到:`AttributeError:'int'对象没有属性'rsplit'。我怎么能这样做,还是有其他选择?

python python-3.x binary-search-tree stdout preorder
1个回答
1
投票

以下是仅在元素之间打印空间的一种方法:

if root:
    if node != root:
       sys.stdout.write(' ')
    sys.stdout.write(str(node.data))
    pre_order(node.left)
    pre_order(node.right)
© www.soinside.com 2019 - 2024. All rights reserved.