我无法将变量从整数转换为字符串

时间:2014-01-08 05:53:40

标签: string variables python-2.7 integer

这是代码:

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'

如果我将其更改为字符串,那么我的if语句将无效。对不起,如果之前已经问过这个问题。感谢。

1 个答案:

答案 0 :(得分:0)

虽然您需要a为逻辑整数,但您需要将其作为字符串仅用于表示目的。所以只有在打印时才转换它。你有几种方法可以做到这一点,你当然知道。其中一些:

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

print('%s bytes' % a)

print(str(a) + ' bytes')
相关问题