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

寻求使用cipher shift加密随机数字与字母的简单代码

凯撒移位密码实现(支持字母、数字加密)

以下轻量代码可实现同时对大小写字母、数字的移位加密,字符超出所属字符集范围时会自动循环处理,符合你给出的移位规则:

  • 小写字母在a-z范围内循环移位
  • 大写字母在A-Z范围内循环移位
  • 数字在0-9范围内循环移位
  • 非上述类型的字符默认保留不做修改

代码实现(Python)

def shift_cipher(input_str: str, shift: int) -> str:
    res = []
    for c in input_str:
        if c.islower():
            base = ord('a')
            res.append(chr((ord(c) - base + shift) % 26 + base))
        elif c.isupper():
            base = ord('A')
            res.append(chr((ord(c) - base + shift) % 26 + base))
        elif c.isdigit():
            base = ord('0')
            res.append(chr((ord(c) - base + shift) % 10 + base))
        else:
            res.append(c)
    return ''.join(res)

测试验证

你的示例场景:移位参数为-3,输入值为abcdefghijklmnopqrstuvwxyz

运行测试代码:

print(shift_cipher("abcdefghijklmnopqrstuvwxyz", -3))

输出结果:
xyzabcdefghijklmnopqrstuvw

数字加密示例:移位参数为2,输入值为0189,输出为2301

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:15:04