如何將字符串「hello world」打印到一行上,但一次只打印一個字符,以便在每個字母的打印之間存在延遲?我的解決方案要麼導致每行一個字符,要麼一次延遲打印整個字符串。這是我得到的最接近的。如何在一行上一次打印一個字符?
import time
string = 'hello world'
for char in string:
print char
time.sleep(.25)
如何將字符串「hello world」打印到一行上,但一次只打印一個字符,以便在每個字母的打印之間存在延遲?我的解決方案要麼導致每行一個字符,要麼一次延遲打印整個字符串。這是我得到的最接近的。如何在一行上一次打印一個字符?
import time
string = 'hello world'
for char in string:
print char
time.sleep(.25)
這裏有兩個竅門,您需要使用流來獲取正確位置的所有內容,並且還需要刷新流緩衝區。
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")
import sys
import time
string = 'hello world\n'
for char in string:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.25)
下面是Python 3的一個簡單的技巧,因爲你可以指定end
參數print
功能:
>>> import time
>>> string = "hello world"
>>> for char in string:
print(char, end='')
time.sleep(.25)
hello world
玩得開心!結果現在動畫!
爲什麼字符串插值? 'sys.stdout.write(c)'在我的系統上工作得很好。 – Blair 2012-09-05 21:27:05