Source From Here
Question
In Python print will add a \n or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first build a string then print it. I'd like to know how to "append" strings to stdout.
How-To
General way
Leverage model sys to directly output message to stdout:
You may also need to call
to ensure stdout is flushed immediately.
Python 2.6+
From Python 2.6 you can import the print function from Python 3:
This allows you to use the Python 3 solution below.
Python 3
In Python 3, the print statement has been changed into a function. In Python 3, you can instead do:
This also works in Python 2, provided that you've used
from __future__ import print_function. If you are having trouble with buffering, you can flush the output by adding flush=True keyword argument:
Question
In Python print will add a \n or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first build a string then print it. I'd like to know how to "append" strings to stdout.
How-To
General way
Leverage model sys to directly output message to stdout:
- import sys
- sys.stdout.write('.')
- sys.stdout.flush()
Python 2.6+
From Python 2.6 you can import the print function from Python 3:
- from __future__ import print_function
Python 3
In Python 3, the print statement has been changed into a function. In Python 3, you can instead do:
- print('.', end='')
- print('.', end='', flush=True)
This message was edited 3 times. Last update was at 20/05/2017 10:48:14
沒有留言:
張貼留言