2011-01-07 107 views
2

我想,如果它只是被輸入要顯示的文字之間有點延遲。所以我在每封信後都需要一點點延遲。打印字符串的字符

我試圖做這樣說:

import time 

text = "Hello, this is a test text to see if all works fine." 
for char in text: 
    print char,time.sleep(0.2), 

它工作正常,除了一個問題。每個角色後我都會得到一個「無」。

這是輸出:

ħ首屈一指e無升無升無○無,無無噸無ħ無I無S無無我無S無無一無無噸首屈一指e無S無噸無無噸首屈一指e無X無噸無無噸無○無無S首屈一指e首屈一指e無無我無˚F無無A無升無升無無瓦特無ö無R無ķ無S無無˚F無I無n無e無。無

我不知道爲什麼會這樣。我希望任何人都可以幫助我。

+0

你爲什麼要打印`time.sleep(0.2)`的值? – 2011-01-07 16:01:03

回答

12
>>> import time 
>>> import sys 
>>> blah = "This is written slowly\n" 
>>> for l in blah: 
... sys.stdout.write(l) 
... sys.stdout.flush() 
... time.sleep(0.2) 
... 
This is written slowly 
+0

用於flush()的+1。當然,如果你真的想讓它看起來像打字,暫停的時間應該是隨機的;誰以完美的定期步伐輸入? – geoffspear 2011-01-07 15:31:09

+0

取決於打字員。家庭按鍵式打字員:在相同的手指按鍵之間的延遲會更大,並且可能在交替的雙手之間最短。更長的延遲等轉移等我開始編碼的東西了,但後來決定回去工作:) – MattH 2011-01-07 15:37:51

1

time.sleep在一個單獨的線。用逗號打印它的返回值。

3

要打印的time.sleep(0.2)的結果,這是None。將它移動到下一行。

text = "Hello, this is a test text to see if all works fine." 
for char in text: 
    print char, 
    time.sleep(0.2) 

當然,你仍然有每個字符之間的空間,這可以通過對sys.stdout.write調用替換print聲明要解決的問題。

text = "Hello, this is a test text to see if all works fine." 
for char in text: 
    sys.stdout.write(char) 
    time.sleep(0.2) 
1

您正在打印time.sleep(0.2)的返回值,即None。把它放在一個單獨的行。 「print char」後面的逗號將防止打印換行符,但它會在每個字符後面引入一個空格。

試試這個:

>>> import sys 
>>> import time 
>>> text = "Hello, this is a test text to see if all works fine." 
>>> for char in text: 
...  sys.stdout.write(char) 
...  time.sleep(0.2) 
1

你的榜樣打印他們都在不同的行我認爲(至少在Windows上)。你可以使用打印到sys.stdout來解決這個問題。

​​
1

這一行:

print char, time.sleep(0.2) 

解碼爲 「打印char的值,然後打印功能time.sleep()(這是None)的返回值」。

你可以將它們分成不同的行,但print後跟一個逗號的默認行爲會讓你在你可能不想要的字符之間留下空格。如果沒有,查找如何改變print行爲,或做這樣的事情:

>>> import sys 
>>> import time 
>>> for char in "test string\n": 
... sys.stdout.write(char) 
... time.sleep(0.2) 
... 
test string 
>>> 
0

謝謝大家的幫助,這是我最後的代碼,我爲延遲隨機的時機,通過提到Wooble:

import time 
import sys 
from random import randrange 

text = "This is the introduction text." 

for c in text: 
    sys.stdout.write(c) 
    sys.stdout.flush() 
    seconds = "0." + str(randrange(1, 4, 1)) 
    seconds = float(seconds) 
    time.sleep(seconds)