2014-01-08 27 views
-1

這是代碼:我無法將變量從整數轉換成字符串

import time 
import os 
os.system("cls") 
a=1 
while True: 
    if a>512: 
     a=1 
     print (a + " kb") 
    if a<1024: 
     print (a + " bytes") 
    a *= 2 
    time.sleep(.5) 

但它給我這個錯誤:

> Traceback (most recent call last): 
>  File "Sequence1.py", line 10, in <module> 
>   print (a + " bytes") 
>  TypeError: unsupported operand type(s) for +: 'int' and 'str' 

如果我把它改成一個字符串,然後如果我聲明不起作用。對不起,如果這個問題之前已經問過。謝謝。

+1

'「{0} bytes」.format(a)'。 :/ – Amelia

+1

鏈接下列網站可能很有用。 http://stackoverflow.com/questions/20441035/unsupported-operand-types-for-int-and-str – Jamescode0b

回答

0

雖然您需要a爲您的邏輯整數,但您只需將它作爲字符串用於表示目的。所以只有在打印時才進行轉換。如你所知,你有幾種方法可以做到這一點。其中一些:

print('{0} bytes'.format(a)) 

print('%s bytes' % a) 

print(str(a) + ' bytes') 
+0

謝謝,我編輯的吧:) –

+0

好吧,我去了三線,現在怎麼辦我繼續說它後kb? – DBK