Python调用encrypt函数遇TypeError: string indices must be integers错误求助
问题排查与解决
错误根源
你遇到的TypeError: string indices must be integers完全是因为这行错误代码:
if i == text[range(len(text))]:
字符串的索引只能是整数类型,但你传入了range(len(text))——这是一个range对象,Python无法用它来定位字符串中的字符,因此抛出类型错误。
同时你的代码逻辑混乱:遍历字母表的每个字符,却试图和整个文本的索引范围做匹配,这根本无法实现加密功能。
修复方案
假设你想实现基础的字符替换加密(比如凯撒密码),以下是修正后的可运行代码:
修正代码(凯撒密码示例)
def encrypt(): text = input("Type your message:\n").lower() alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] encrypted = "" # 遍历输入文本的每个字符 for char in text: if char in alphabet: # 移位3位,可自行修改移位量 idx = alphabet.index(char) encrypted += alphabet[(idx + 3) % 26] else: # 非字母字符直接保留 encrypted += char print("加密后的消息:", encrypted) encrypt()
核心修正点
- 删除了错误的
text[range(len(text))]写法,改为遍历输入文本的每个字符 - 补充了合理的加密逻辑(以凯撒密码为例),如果不需要移位,可直接保留原字符
- 处理了非字母字符,避免程序崩溃
如果你的需求只是打印输入中的字母字符,用这段简化代码即可:
def encrypt(): text = input("Type your message:\n").lower() alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] for char in text: if char in alphabet: print(char) encrypt()
内容的提问来源于stack exchange,提问作者Amrassad
相关产品推荐
相关产品推荐

