无法在python中使用“chr”

时间:2015-12-16 14:34:08

标签: python

我之前在我的代码中遇到过错误,我现在已经排序了,但是现在我运行了我的代码,出现了一个新的错误

  

string =(chr(addition))   TypeError:需要一个整数(得到类型str)

我不知道为什么会出现这种情况,如果有人有解决方案或想法如何修复此代码,我将不胜感激。

它遇到问题的行是string = (chr(addition))

完整的代码发布在下面。

alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ0123456789"
choice = input("Would you like to encrypt or decrypt? [e/d]: ")
string = ''
key1 = ''
message1 = ''
if choice == "e":
    message = input("Please insert the message you would like to use: ")
    keyword = input("Please insert the keyword you would like to use: ")
    for A in message:
        if message in alphabet:
            message1 = (ord(message)) - 96
        for A in keyword:
            if keyword in alphabet:
                key1 = (ord(keyword)) - 96
    addition = key1 + message1
    string = (chr(addition))
    print (string)

2 个答案:

答案 0 :(得分:2)

您将key1message1初始化为字符串。

key1 = ''
message1 = ''

如果未覆盖这些值,addition = key1 + message1也将是一个字符串,因此chr(addition)将获取一个字符串作为参数,如错误消息所述。您可以通过debugging

轻松找到这些错误

热修复可能会将它们初始化为零,例如:

key1 = 0
message1 = 0

答案 1 :(得分:0)

这会更像你想要的吗?

每次加密字母时,它都会循环显示关键字的一个字母。一旦它耗尽了所有关键字字母,它就会回到开头(last if语句)。
我没有在message1中添加任何值,也没有在key1值中添加任何值,因为您应该决定什么符合您的加密条件。由于Python 3编码为Unicode而不是ASCII,因此可以将chr()函数值传递到255以上。但是,最好注意到你不能低于0,因为当你减去96两次时,它会发生在你之前的代码中。从关键字字母和消息字母)。如果低于0将使解释器吐出一个ValueError,它恰好说明了。

alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ0123456789"
choice = input("Would you like to encrypt or decrypt? [e/d]: ")

if choice == "e":

        message = input("Please insert the message you would like to use: ")
        keyword = input("Please insert the keyword you would like to use: ")    
        ik = len(keyword)
        i = 0
        string = ''

        for A in message:

            message1 = (ord(A))
            key1 = (ord(keyword[i]))

            addition = message1 + key1            
            string += (chr(addition))

            if i >= ik:
                i = 0
            else:
                i += 1

        print (string)

如果您想要解密您的消息,则只需减去键值:

elif choice == "d":

        message = input("Please insert the message you would like to use: ")
        keyword = input("Please insert the keyword you would like to use: ")

        ik = len(keyword)
        i = 0
        string = ''

        for A in message:

            message1 = (ord(A))
            key1 = (ord(keyword[i]))

            addition = message1 - key1          
            string += (chr(addition))

            if i >= ik:
                i = 0
            else:
                i += 1

        print (string)