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

如何在Python中为凯撒密文添加随机大写字母(密码生成器开发)

实现密文随机大写功能的解决方案

核心思路

先通过凯撒加密得到密文,再遍历密文中的每个字符,仅对字母类字符随机决定是否转为大写(非字母字符直接保留),利用Python的random模块实现随机性。

修改后的完整代码

import random

def caesar_encryption(plaintext, key):
    encryption_str = ''
    for i in plaintext:
        if i.isupper():
            temp = 65 + ((ord(i) - 65 + key) % 26) 
            encryption_str += chr(temp)                              
        elif i.islower():
            temp = 97 + ((ord(i) - 97 + key) % 26)
            encryption_str += chr(temp)
        else:
            encryption_str += i  
    # 改为返回密文,而非直接打印,方便后续处理
    return encryption_str

def random_upper_cipher(ciphertext):
    result = ''
    for char in ciphertext:
        if char.isalpha():
            # 随机选择转为大写或保持原格式,默认50%概率
            result += random.choice([char.upper(), char])
        else:
            result += char
    return result

# 主流程
plaintext = input("Enter the Website Name:")
key = int(input("Enter the key:"))
# 先执行凯撒加密
cipher = caesar_encryption(plaintext, key)
# 处理随机大写
final_cipher = random_upper_cipher(cipher)
print("The ciphertext with random uppercase:", final_cipher)

关键说明

  1. 调整凯撒加密函数:将原函数的print输出改为返回密文字符串,让后续流程能直接调用密文进行处理。
  2. 自定义随机概率:
    默认代码是50%概率转大写,如果需要调整比例(比如30%概率转大写),可以替换随机逻辑为:
    if random.random() < 0.3:
        result += char.upper()
    else:
        result += char
    
  3. 扩展性兼容:后续可以直接在final_cipher的基础上拼接用户指定的数字、符号,快速完成最终密码生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:55:24