Python For循环无法识别字符串特殊字符导致空格被错误编解码
问题根因
你代码里的特殊字符判断逻辑完全错误,导致所有字符都会进入编解码分支,没有例外。
你写的if x!=" " or "," or "."在Python中的实际执行逻辑是:
- 先判断
x != " "的布尔值 - 再判断非空字符串
","的布尔值,固定为True - 最后判断非空字符串
"."的布尔值,固定为True
只要三个子条件有一个为真,整个or连接的条件就为真,所以不管x是不是空格/逗号/句号,这个if判断永远成立,特殊字符也会被转成ASCII码参与移位,才会出现空格变逗号、逗号变冒号的问题。
修复方案
把所有判断特殊字符的if条件,替换成逻辑正确的写法:if x not in (" ", ",", "."),如果要保留不等于的写法,必须写成if x != " " and x != "," and x != ".",注意要用and而非or。
修复后完整代码
def encode(string,key): arr=[] for x in string: if x not in (" ", ",", "."): ascii_val = ord(x) if ascii_val + key > 90: arr.append(chr(64 + ((ascii_val + key) - 90))) else: arr.append(chr(ascii_val + key)) else: arr.append(x) print(''.join(arr)) def decode(string,key): arr=[] for x in string: if x not in (" ", ",", "."): ascii_val = ord(x) if ascii_val - key < 65: arr.append(chr(90 - (64 - (ascii_val - key)))) else: arr.append(chr(ascii_val - key)) else: arr.append(x) print(''.join(arr)) while True: string = input("enter string: ") string = string.upper() key = int(input("enter key: ")) switchCase = input("encode/decode?: ") if switchCase == "encode": encode(string, key) elif switchCase == "decode": decode(string, key) elif switchCase == "exit": break
内容的提问来源于stack exchange,提问作者Lasagne
相关产品推荐
相关产品推荐

