Print in Python3

Print in Python3

There are two kinds of ways to output to the screen, one is sys.output.write and print. When we use print, this built-in function actually calls the stdout function.

print equals stdout.write plus "\n". However, when we call print, we can change the optional parameter to print multi objects into a single line.

See the doc of print:

  • print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

To get the print without newline:

1
print("your output",end=" ")

My use experience:

See my exercise in the binary search tree, I want to travelsal the tree node and output into a single line.

1
2
3
4
5
6
7
8
9
10
    def preOrderTraversal(self,node):
'''
if you want to output the node in a single line:
- change the `print` to `print(node.data,end=' ')
'''
if node:
# print(node.data)
print(node.data,end=" ")
self.preOrderTraversal(node.lchild)
self.preOrderTraversal(node.rchild)