2017年5月19日 星期五

[ Python 常見問題 ] How to print without newline or space?

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:
  1. import sys  
  2. sys.stdout.write('.')  
You may also need to call
  1. sys.stdout.flush()  
to ensure stdout is flushed immediately.

Python 2.6+
From Python 2.6 you can import the print function from Python 3:
  1. from __future__ import print_function  
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:
  1. print('.', end='')  
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:
  1. print('.', end='', flush=True)  

This message was edited 3 times. Last update was at 20/05/2017 10:48:14

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...