2012-02-12 15 views
18

"hello world"という文字列を1行に印刷する方法はありますが、各文字の印刷の間に遅延が生じるように一度に1文字ですか?私の解決策は、1行に1文字、または文字列全体を一度に遅らせることです。これは私が得た最も近いものです。ここ1行に1文字ずつ印刷する方法は?

import time 
string = 'hello world' 
for char in string: 
    print char 
    time.sleep(.25) 

答えて

27

つのトリック、あなたは正しい場所にすべてを取得するためのストリームを使用する必要があります。また、ストリームバッファをフラッシュする必要があります。

import time 
import sys 

def delay_print(s): 
    for c in s: 
     sys.stdout.write(c) 
     sys.stdout.flush() 
     time.sleep(0.25) 

delay_print("hello world") 
+5

なぜ文字列の補間ですか? 'sys.stdout.write(c)'は私のシステムでうまく動作します。 – Blair

4
import sys 
import time 

string = 'hello world\n' 
for char in string: 
    sys.stdout.write(char) 
    sys.stdout.flush() 
    time.sleep(.25) 
5

あなたがprint機能のendパラメータを指定することができますので、ここでは、Pythonの3のための簡単なトリックです:

>>> import time 
>>> string = "hello world" 
>>> for char in string: 
    print(char, end='') 
    time.sleep(.25) 


hello world 

は、お楽しみに!結果は今アニメーション化されています!

関連する問題