如何在编码句子时保留空格和特殊字符
How to keep spaces and special characters while encoding a sentence
所以我正在尝试制作一个 encoding/decoding 程序,让用户键入一个句子并通过用其他字母替换字母将其变成编码消息。
用一个词可以正常工作,但是当我输入更多带有空格和特殊字符的词时,它似乎不起作用。
这是我的代码:
phrase = input("Write a sentence:")
decalage = int(input("By how many letters (1 to replace a with b...): "))
maping = {}
for i in range(26):
i_cesar = (i + decalage) % 26
c_cesar = chr(i_cesar + ord('a'))
c = chr(i + ord('a'))
maping[c] = c_cesar
result = ""
for c in phrase:
result = result + maping[c]
print(result)
如果我正确理解您的要求,我认为这整个事情可以简化为只添加到字符的数字表示,但仅限于字符是字母的情况。
像下面这样的事情会更容易一些:
phrase = input("Write a sentence:")
decalage = int(input("By how many letters (1 to replace a with b...): "))
result = ""
for c in list(phrase):
if ord(c) >= 65 and ord(c) <= 122:
result = result + chr(ord(c)+decalage)
else:
result + c
print(result)
您只是在为小写字母构建映射。您可以做的一件事是将您打算更改的所有字符组成一个字符串,然后旋转该字符串的副本以形成您的字典。
from string import ascii_lowercase, digits, punctuation
characters = ascii_lowercase + digits + punctuation
def rotate(s: str, degree: int) -> str:
return s[degree:] + s[:degree]
def cesar_encode(plaintext: str, cipher: int) -> str:
mapping = dict(zip(characters, rotate(characters, cipher)))
return "".join([mapping.get(c, c) for c in plaintext])
cesar_encode("abcde12345$%^&", 1)
# "bcdef23456%&_'"
所以我正在尝试制作一个 encoding/decoding 程序,让用户键入一个句子并通过用其他字母替换字母将其变成编码消息。
用一个词可以正常工作,但是当我输入更多带有空格和特殊字符的词时,它似乎不起作用。
这是我的代码:
phrase = input("Write a sentence:")
decalage = int(input("By how many letters (1 to replace a with b...): "))
maping = {}
for i in range(26):
i_cesar = (i + decalage) % 26
c_cesar = chr(i_cesar + ord('a'))
c = chr(i + ord('a'))
maping[c] = c_cesar
result = ""
for c in phrase:
result = result + maping[c]
print(result)
如果我正确理解您的要求,我认为这整个事情可以简化为只添加到字符的数字表示,但仅限于字符是字母的情况。
像下面这样的事情会更容易一些:
phrase = input("Write a sentence:")
decalage = int(input("By how many letters (1 to replace a with b...): "))
result = ""
for c in list(phrase):
if ord(c) >= 65 and ord(c) <= 122:
result = result + chr(ord(c)+decalage)
else:
result + c
print(result)
您只是在为小写字母构建映射。您可以做的一件事是将您打算更改的所有字符组成一个字符串,然后旋转该字符串的副本以形成您的字典。
from string import ascii_lowercase, digits, punctuation
characters = ascii_lowercase + digits + punctuation
def rotate(s: str, degree: int) -> str:
return s[degree:] + s[:degree]
def cesar_encode(plaintext: str, cipher: int) -> str:
mapping = dict(zip(characters, rotate(characters, cipher)))
return "".join([mapping.get(c, c) for c in plaintext])
cesar_encode("abcde12345$%^&", 1)
# "bcdef23456%&_'"