Python中如何将输入文本字符在字母列表中的位置值存入另一个列表(凯撒密码场景)
Python中如何将输入文本字符在字母列表中的位置值存入另一个列表(凯撒密码场景)
嗨,我看你在做凯撒密码的过程中,卡在了把输入文本的每个字符对应字母列表的位置存入新列表这一步,咱们来一步步捋清楚问题出在哪,以及怎么解决它~
先说说你遇到的错误原因
你写的这段代码里:
for i in text: text_catch.append(alphabet.index(text[i-1]))
这里的i是text里的每个字符(比如输入hello的话,i会依次是'h'、'e'、'l'、'l'、'o'),它是字符串类型的,你尝试用i-1,相当于让字符串减整数,Python肯定不支持这种操作,所以才会报TypeError: unsupported operand type(s) for -: 'str' and 'int'这个错。
正确的实现方式
其实不用搞那么复杂的while循环,用for循环直接遍历每个字符就很清晰,而且能轻松把位置存入列表:
基础版(假设输入全是字母)
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'] direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) text_catch = [] # 遍历输入文本的每个字符 for char in text: # 直接获取当前字符在字母列表中的索引 char_index = alphabet.index(char) text_catch.append(char_index) print("每个字符的位置列表:", text_catch)
这样运行输入hello的话,text_catch就会得到[7, 4, 11, 11, 14],完全符合你的需求~
进阶版(支持非字母字符,比如空格、数字)
如果输入里可能有非字母的内容(比如hello world!),直接用index会报错,咱们可以加个判断,遇到非字母就直接保留原字符:
text_catch = [] for char in text: if char in alphabet: char_index = alphabet.index(char) text_catch.append(char_index) else: # 非字母字符,直接存原字符(或者你也可以按需求处理) text_catch.append(char)
结合凯撒密码的完整逻辑
拿到位置列表后,咱们就可以继续完成加密/解密的功能了,这里给你补全完整的示例代码:
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'] direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) text_catch = [] for char in text: if char in alphabet: text_catch.append(alphabet.index(char)) else: text_catch.append(char) # 处理加密/解密 result = [] for item in text_catch: if isinstance(item, int): if direction == 'encode': # 加密:移位后取模避免超出列表范围 new_index = (item + shift) % 26 elif direction == 'decode': # 解密:反向移位同样取模 new_index = (item - shift) % 26 result.append(alphabet[new_index]) else: # 非字母直接添加 result.append(item) print("最终结果:", ''.join(result))
总结一下
你之前的问题核心是搞混了循环变量的类型——用for i in text时,i是字符不是索引,直接用字符去字母列表找索引就好,不用再通过索引去取字符啦~
备注:内容来源于stack exchange,提问作者Greystone
相关产品推荐
相关产品推荐

