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
"""