简体   繁体   English

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

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

I'm printing an output using stdout in python, but it keeps the things it keeps printing has whitespace at the end, and rsplit() always gives me an error.我正在使用 python 中的 stdout 打印输出,但它保留它保持打印的内容最后有空格,并且rsplit()总是给我一个错误。 Code Below.代码如下。



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)

I with the input 7 898 157 397 57 178 26 679 I get the output 178 57 26 157 679 397 898. The .我输入7 898 157 397 57 178 26 679我得到输出178 57 26 157 679 397 898. . is to illustrate the whitespace, but note in the actual output it is just a blank space.是为了说明空格,但请注意在实际输出中它只是一个空格。 I've tried to我试过
sys.stdout.write(node.data + ' ').rsplit() but get the: `AttributeError: 'int' object has no attribute 'rsplit'. sys.stdout.write(node.data + ' ').rsplit()但得到:`AttributeError: 'int' object has no attribute 'rsplit'。 How can I do this, or are there any alternatives?我该怎么做,或者有其他选择吗?

Here is one way to print a space only between elements:这是仅元素之间打印空格的一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM