checkio练习题:007-caesar-cipher-encryptor

本文详细介绍了凯撒加密算法的工作原理,包括如何使用固定距离替换输入文本中的每个字母进行加密。通过具体示例展示了加密过程,并提供了Python实现代码。适用于初学者理解基本的加密技术和信息安全概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This mission is the part of the set. Another one - Caesar cipher decriptor.

Your mission is to encrypt a secret message (text only, without special chars like "!", "&", "?" etc.) using Caesar cipher where each letter of input text is replaced by another that stands at a fixed distance. For example ("a b c", 3) == "d e f"

example

Input: A secret message as a string (lowercase letters only and white spaces)

Output: The same string, but encrypted

Example:

to_encrypt("a b c", 3) == "d e f"
to_encrypt("a b c", -3) == "x y z"
to_encrypt("simple text", 16) == "iycfbu junj"
to_encrypt("important text", 10) == "swzybdkxd dohd"
to_encrypt("state secret", -13) == "fgngr frperg"

How it is used: For cryptography and to save important information.

Precondition:
0 < len(text) < 50
-26 < delta < 26

 

def to_encrypt(text, delta):
    cipher = ''
    for char in text:
        if char == ' ':
            cipher = cipher + char
        elif char.isupper():
            cipher = cipher + chr((ord(char) + delta - 65) % 26 + 65)
        else:
            cipher = cipher + chr((ord(char) + delta - 97) % 26 + 97)
    return cipher


if __name__ == '__main__':
    print("Example:")
    print(to_encrypt('hello joyce, can you tell me why?', 12))

    # These "asserts" using only for self-checking and not necessary for auto-testing
    assert to_encrypt("a b c", 3) == "d e f"
    assert to_encrypt("a b c", -3) == "x y z"
    assert to_encrypt("simple text", 16) == "iycfbu junj"
    assert to_encrypt("important text", 10) == "swzybdkxd dohd"
    assert to_encrypt("state secret", -13) == "fgngr frperg"
    print("Coding complete? Click 'Check' to earn cool rewards!")

"""
ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,
它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,
如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。
>>>ord('a')
97
>>>ord('z')
122
>>>ord('A')
65
>>>ord('Z')
90
chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符。
>>> print chr(48), chr(57), chr(97)         # 十进制
0 9 a
"""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值