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

如何调用已有的build_cipher函数实现Python字符串移位加密encode功能

实现思路

  1. 首先调用build_cipher(shift)生成明文字母到密文字母的映射字典
  2. 遍历输入文本text中的每一个字符,通过映射字典查询对应的加密字符
  3. 将所有加密后的字符拼接为完整字符串返回即可

完整实现代码

def encode(text, shift):
    '''
    Description: takes in a text string and shift. Returns the text string encoded based on the shift.
    
    >>> encode('test', -4)
    'paop'
    >>> encode('code', 5)
    'htij'
    '''
    # 生成加密映射字典
    cipher_map = build_cipher(shift)
    # 遍历每个字符查表,拼接得到加密结果
    encoded_text = ''.join([cipher_map[char] for char in text])
    return encoded_text

如果需要兼容非字母字符、大小写混合的输入,可以修改字符映射逻辑,遇到不在映射表中的字符直接保留原值:

encoded_text = ''.join([cipher_map.get(char.lower(), char) for char in text])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:57:03