我正在使用python尝试制作一个Caeser Cipher程序。 所以我已经建立了一个GUI平台,并且能够使密码部分工作,但它只以ASCII格式发出消息。
当你运行我的程序时,它会获取信息,你说你希望字母表移动的字母数量,然后用ASCII表示消息,我怎样才能让这部分以字母形式出现?
我尝试将for循环存储到变量中,然后将该变量添加到常见的ascii中 - >字符转换器,但这不起作用。
这是我的代码:
def encode(userPhrase):
msg = input('Enter your message: ')
key = eval(input("enter a number"))
finalmsg = msg.upper()
for ch in finalmsg:
print( str( ord(ch)+key ), end=' ')
答案 0 :(得分:1)
将您的str
更改为chr
:
print( chr( ord(ch)+key ), end=' ')
根据chr的文档:
返回表示Unicode代码点为整数i的字符的字符串。例如,chr(97)返回字符串'a',而chr(957)返回字符串'ν'。这是ord()的反转。
答案 1 :(得分:0)
你需要允许字母表末尾的字母环绕到A,B,C ...你可以用模运算(复杂)来做,或者看下面的例子
使用chr
代替str
。您传递参数userPhrase
并要求输入消息。另外,我建议使用int
代替eval
。
def encode(userPhrase):
msg = input('Enter your message: ')
key = int(input("enter a number"))
finalmsg = msg.upper()
for ch in finalmsg:
new_ch = ord(ch)+key
if new_ch > ord('Z'):
new_ch -= 26
print( chr(new_ch), end=' ')
你遇到的最后一个问题是非字母(例如空格等)