Python代码返回换行及二进制编码空串问题,请求调试帮助
问题调试与修复
一、编码功能返回空串的问题及修复
核心bug分析
- 字符遍历逻辑错误:编码部分用
string.split()分割输入,会把无空格的输入(如"A)")当成单个元素,而你的匹配列表都是单个字符,导致循环中没有匹配项,encoded始终为空。 index()方法调用错误:所有symbols.index()、upper.index()等调用都缺少要查找的字符参数c,即使遍历逻辑正确也会触发TypeError。- 结果拼接冗余空格:直接用
" " + ibin拼接会导致结果开头多出一个空格,影响输出格式。
修复后的完整代码
import json symbols = [" ", "!", '"', "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@"] letters = ["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"] upper = list(map(lambda x: x.upper(), letters)) after = ["{", "|", "}", "~"] symbol_sub = 32 upper_sub = 65 lower_sub = 97 after_sub = 123 choice = input("Do you want to encode text, or decode it? e, or d? ").lower() if choice == 'e': string = input("Type in your text: ") encoded_parts = [] # 遍历输入的每个单个字符,而非按空格分割后的元素 for c in string: if c in symbols: i = symbols.index(c) + symbol_sub ibin = bin(i).split('0b')[1] encoded_parts.append(ibin) elif c in upper: i = upper.index(c) + upper_sub ibin = bin(i).split('0b')[1] encoded_parts.append(ibin) elif c in letters: i = letters.index(c) + lower_sub ibin = bin(i).split('0b')[1] encoded_parts.append(ibin) elif c in after: i = after.index(c) + after_sub ibin = bin(i).split('0b')[1] encoded_parts.append(ibin) # 用空格连接所有二进制串,避免开头冗余空格 encoded = " ".join(encoded_parts) print(encoded) elif choice == 'd': string = input("Please input your binary code, each binary string separated by spaces: ") allbits = string.split(' ') decoded = '' for i in allbits: b10 = int(i, 2) if b10 - after_sub < 0: if b10 - lower_sub < 0: if b10 - upper_sub < 0: decoded += symbols[b10 - symbol_sub] else: decoded += upper[b10 - upper_sub] else: decoded += letters[b10 - lower_sub] else: decoded += after[b10 - after_sub] print(decoded)
测试输入"A)"时,输出为1000001 101001,符合预期。
二、代码返回换行的问题
Python的print()函数默认会在输出末尾添加换行符,这是标准行为。如果不需要输出末尾的换行,可以修改print语句为:
print(encoded, end='')
如果是指输出内容中出现意外换行,检查输入时是否误输入了换行符,或者确保处理字符时没有引入换行相关的字符。
内容的提问来源于stack exchange,提问作者Dark Shadow
相关产品推荐
相关产品推荐

