TypeError:无法转换' int'隐含地反对str

时间:2016-03-05 18:28:09

标签: python python-3.x typeerror

我正在编写一个用两个关键字加密文本文件的程序。我的代码未完成,但加密时出错。

我的代码:

while True:
    print('Do you wish to encrypt or decrypt your textfile?')
    option = input().lower()
    if option in ["e","encrypt","d","decrypt"]:
        break
    else:
        print('Enter again')


key1 = input("Enter your first keyword ").upper()
if len(key1) == 0:
      print ('Your keyword has to be more than one character. Enter again')

key1 = ([ord(k) for k in key1])
key1 = (key1)*100
print (key1)

key2 = input("Enter your second keyword ").upper()
if len(key2) == 0:
    print ('Your keyword has to be more than one character. Enter again')

key2 = ([ord(e) for e in key2])
key2 = (key2)*100
print (key2)

efile = input('Enter the text file you want to change (with .txt)')
efile = open(efile).read()
efile = efile.upper()

k = 0
e = 0

string = ''
for symbol in efile:
    ctext = ord(symbol)
    if ctext == 32:
        ctext = chr(ctext)
        ctext = str(ctext)
        string += ctext
#print(string)

else:
    while len(string)> 0:
        ctext += key1[k]
        if ctext > 90:
            ctext -= 64
        ctext += key2[e]
        if ctext > 90:
            ctext -= 64
        ctext = chr(ctext)
        ctext = str(ctext)
        string += ctext
        k+=1
        e+=1
print(ctext)


   ctext += key1[k]

Python在运行我的代码时抛出以下错误:

TypeError: Can't convert 'int' object to str implicitly

如果有人能给我建议解决这个问题,我会非常感激,因为我不知道! :)

1 个答案:

答案 0 :(得分:0)

如果ctext等于32,您将其转换为string,当for循环耗尽时,正在执行else范围正试图跑:

ctext += key1[k]  # ctext is a string, key1[k] is an int

同样:

# Python 3
variable = '2'  
variable += 1
>> TypeError: Can't convert 'int' object to str implicitly