2012-12-30 60 views
0

我試圖依次顯示python中給定字符串的位。我可以將其轉換爲二進制字符串,但不能用計時器枚舉它。用python顯示python中的一串字符串

這裏的基於代碼的最小示例我使用:

import sys 
string = "a" 
for char in string: 
    mybyte = str(bin(ord(char))[2:].zfill(8)) // convert char to 8 char length string which are char's representation in binary 
    for bit in mybyte: 
     sys.stdout.write(bit) 
     time.sleep(0.5) 

    sys.stdout.write("\n") 

這並不表明由0.5秒分離的每個位,但等到所有位(8×0.5 = 4秒)已經被處理以給他們看。

但是,如果我在lop中放了一個新行,我會得到一個及時的正確迭代,但需要在每個位之間插入新行,這是我不想要的。我猜我在這裏做錯了,就像沒有問題的好方法,但我真的被困在這個,所以任何建議是值得歡迎的。

回答

0

您需要sys.stdout.flush()每次寫入的標準輸出是默認

0

緩衝後,您可能需要刷新sys.stdout

import sys 
string = "a" 
for char in string: 
    mybyte = str(bin(ord(char))[2:].zfill(8)) // convert char to 8 char length string which are char's representation in binary 
    for bit in mybyte: 
     sys.stdout.write(bit) 
     sys.stdout.flush() # <-- Add this line right here 
     time.sleep(0.5) 

    sys.stdout.write("\n") 

對於Python 3,你可以只使用end關鍵字參數print()

import sys 
string = "a" 

for char in string: 
    mybyte = str(bin(ord(char))[2:].zfill(8)) 

    for bit in mybyte: 
     print(bit, end='') 
     time.sleep(0.5) 

    print() 

對於Python 2,您必須導入打印功能:

from __future__ import print_function