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

How to get rid of trailing whitespace printing a list using stdout python3

我在 python 中使用 stdout 打印输出,但它保持打印的内容在末尾有白色 space,并且 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. . 是为了说明白色space,但注意在实际输出中它只是一个空白space。我试过
sys.stdout.write(node.data + ' ').rsplit() 但得到: `AttributeError: 'int' 对象没有属性 'rsplit'。 我该怎么做,或者有其他选择吗?

这是一种仅在 元素之间打印 space 的方法:

if root:
    if node != root:
       sys.stdout.write(' ')
    sys.stdout.write(str(node.data))
    pre_order(node.left)
    pre_order(node.right)