寻求使用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
相关产品推荐
相关产品推荐

