You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于ASCII值的加解密程序问题:仅输出字符串首字符

问题修复:ASCII加密解密程序仅输出第一个字符的解决方法

核心问题分析

  1. encrypt函数的return语句缩进错误:你把return en写在了for循环内部,导致程序处理完字符串的第一个字符就直接返回结果,不会继续遍历剩余字符。
  2. decrypt函数逻辑冗余错误:该函数先调用encrypt加密输入文本再解密,完全不符合解密逻辑,解密应该直接对传入的密文进行逆运算。

修正后的完整代码

# 加密函数
def encrypt(text, shift):
    en = ""
    for i in text:
        if 65 <= ord(i) <= 90:  # 大写字母处理
            temp = ord(i) + shift
            if temp > 90:
                temp = temp % 90 + 64
            en += chr(temp)
        elif 97 <= ord(i) <= 122:  # 小写字母处理
            temp = ord(i) + shift
            if temp > 122:
                temp = temp % 122 + 96
            en += chr(temp)
        else:  # 其他字符直接偏移
            en += chr(ord(i) + shift)
    return en  # 移到循环外部,遍历完所有字符再返回

# 解密函数
def decrypt(text, shift):
    de = ""
    for i in text:
        if 65 <= ord(i) <= 90:  # 大写字母解密
            de += chr((ord(i) - shift - 65) % 26 + 65)
        elif 97 <= ord(i) <= 122:  # 小写字母解密
            de += chr((ord(i) - shift - 97) % 26 + 97)
        else:  # 其他字符直接逆偏移
            de += chr(ord(i) - shift)
    return de

测试示例

# 测试加密
plain_text = "Hello, World!"
shift_num = 3
cipher_text = encrypt(plain_text, shift_num)
print(f"加密后:{cipher_text}")  # 输出:Khoor, Zruog!

# 测试解密
decrypted_text = decrypt(cipher_text, shift_num)
print(f"解密后:{decrypted_text}")  # 输出:Hello, World!

内容的提问来源于stack exchange,提问作者Kay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 11:55:18