Python:执行简易ASCII解密时触发TypeError错误求助
编解码算法解密端报错问题
我基于Python的ord函数开发了一套编解码算法,加密端通过将ord函数的输出值乘以随机生成的数字实现,目前可正常运行;但解密端按反向逻辑(使用chr函数)实现时出现错误。
加密工具代码
#Encryption tool import random import os import time import sys import tkinter as tk root = tk.Tk() canvas1 = tk.Canvas(root, width=400, height=300) canvas1.pack() entry1 = tk.Entry(root) canvas1.create_window(200, 140, window=entry1) button1 = tk.Button(text='Encrypt', command=encrypt) def a(): with open("encryptiontool.py") as f: exec(f.read()) txtlen = 0 shiftnum = random.randint(1, 11) os.system("afplay /System/Library/Sounds/Hero.aiff") print("Welcome to SHIFTNUM Encryption Tool! ") encrypt_input = input("Enter a word to be encrypted: ") lengthinput = len(list(encrypt_input)) numberlength = int(lengthinput) if shiftnum == 11: os.system("afplay /System/Library/Sounds/Bottle.aiff") print("!@**#(*!%#(&^%!&^@%ERROR!(@&^^#$%*^!%$&#^%$") sys.exit() encryptedlist = [] print("NUMSHIFT = ", shiftnum) while numberlength > 0: numberlength = numberlength - 1 encryptedlist.append(ord(encrypt_input[txtlen]) * shiftnum) txtlen = txtlen + 1 print(encryptedlist) os.system("afplay /System/Library/Sounds/Glass.aiff")
尝试的解密工具代码(报错版本)
#Decryption tool txtlen = 0 import re numshift = int(input("NUMSHIFT = ")) encryptedtxtlist = input("Paste list here: ") dechartxt = re.sub(r"[^a-zA-Z0-9 ]", "", encryptedtxtlist) print(dechartxt.split()) listlength = len(dechartxt.split()) lstlen = int(listlength) dechar = int(dechartxt) decodedlist = [] while lstlen > 0: lstlen = lstlen - 1 dechar = dechar / numshift decodedlist.append(chr(int(dechar[txtlen]))) txtlen = txtlen + 1 print(decodedlist)
运行报错信息
NUMSHIFT = 5 Paste list here: ['460'] ['460'] Traceback (most recent call last): File "/Users/ruben_sutton29/Desktop/pythonproject/decryptiontool.py", line 19, in <module> decodedlist.append(chr(int(dechar[txtlen]))) TypeError: 'float' object is not subscriptable
错误原因及修正方案
错误点分析
- 输入处理错误:你把整个处理后的字符串转成单个整数
dechar = int(dechartxt),但实际上加密输出是多个数字组成的列表,应该逐个处理每个数字。 - 类型错误:
dechar / numshift会得到浮点数,之后尝试用下标dechar[txtlen]访问,而浮点数不支持下标操作,导致报错。 - 正则替换逻辑缺陷:用正则去掉非字母数字字符会丢失列表的结构,不如直接解析输入的列表字符串更可靠。
修正后的解密代码
#Decryption tool import ast numshift = int(input("NUMSHIFT = ")) encryptedtxtlist = input("Paste list here: ") # 直接解析输入的列表字符串为整数列表 encrypted_nums = ast.literal_eval(encryptedtxtlist) decoded_chars = [] for num in encrypted_nums: # 除以shiftnum后转整数,再转字符 original_ord = int(num / numshift) decoded_chars.append(chr(original_ord)) # 把字符列表拼成字符串输出 decoded_str = ''.join(decoded_chars) print("解密结果:", decoded_str)
代码说明
- 使用
ast.literal_eval安全地解析输入的列表字符串,直接得到整数列表,避免正则处理的麻烦。 - 遍历每个加密后的数字,除以shiftnum后转成整数(确保是有效的ASCII码值),再用
chr转成对应字符。 - 最后将字符列表拼接成字符串,输出更直观的解密结果。
内容的提问来源于stack exchange,提问作者Ruben Sutton
相关产品推荐
相关产品推荐

