如何在编码句子时保留空格和特殊字符
所以我正在尝试制作一个编码/解码程序,让用户输入一个句子并通过用其他字母替换字母将其转换为编码消息。
它适用于一个单词,但当我添加更多带有空格和特殊字符的单词时,它似乎不起作用。
所以这是我的代码:
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)
So I'm trying to make an encoding/decoding program, that lets the user to type a sentence and turn it into an encoding message by replacing letters with other letters.
It works fine with one words, but when I put more words with spaces and special characters it seems to be not working.
So here is my code:
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只是为小写字母构建映射。您可以做的一件事是创建一个包含您想要更改的所有字符的字符串,然后旋转该字符串的副本以形成您的字典。
You're only building a mapping for the lowercase letters. One thing you can do is make a string of all the characters you intend to change, then rotate a copy of that string to form your dictionary.
如果我正确理解您的要求,我认为整个事情可以简化为仅添加到字符的数字表示形式,但仅限于字符是字母的情况。
像下面这样的事情会更容易一些:
If I understand your requirements correctly, I think this whole thing can be simplified to just add to the numeric representation of the character, but only in the case if the character is a letter.
Something like the following would be a little easier: