Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我的代码会打印其他字符?密码_Python - Fatal编程技术网

Python 为什么我的代码会打印其他字符?密码

Python 为什么我的代码会打印其他字符?密码,python,Python,我只想打印字母,但它打印ASCII的特殊字符。我的代码: import string def caesar(shift): alphabet = string.ascii_lowercase + string.ascii_uppercase dict={} emptylist=[] int(shift) for x in alphabet: emptylist.append(x) code = "" for

我只想打印字母,但它打印ASCII的特殊字符。我的代码:

import string
def caesar(shift):
    alphabet = string.ascii_lowercase + string.ascii_uppercase
    dict={}
    emptylist=[]
    int(shift)
    for x in alphabet:
        emptylist.append(x)
        code = ""
        for letters in emptylist:
            code = chr(ord(letters) + shift)
            dict[letters]=code
    return dict
caesar(12)
我的输出:

“m':'y','l':'x','o':'{','n':'z','q':','p':','s':'\x7f','r':'~','u':'\x81','t':'\x80','w':'\x83','v':'\x82','y':'\x85','x':'\x84','z':'\x86'

正确输出:

‘m’:‘y’、‘l’:‘x’、‘o’:‘a’、‘n’:‘z’、‘q’:‘c’、‘p’:‘b’、‘s’:‘e’、‘r’:‘d’、‘u’:‘g’、‘t’:‘f’、‘w’:‘i’、‘v’:‘h’、‘y’:‘k’、‘x’:‘j’、‘z’:‘l’

使用
ord()
并更改字符代码不会将生成的字符限制在词典中

我只要在你的字典中找到字母的索引,移动它,然后使用模运算符:

import string

def caesar(shift):
    alphabet = string.ascii_uppercase  # <- Change it back to what you had before
                                       #    and see what will happen.
    mapping = {}

    for letter in alphabet:
        index = alphabet.index(letter)
        mapping[letter] = alphabet[(index + shift) % len(alphabet)]

    return mapping

让我们特别看一个错误:
o:'{'

注意,
ord('o')
是111,所以让我们看看
范围(111130)
中整数的
chr

o
开始,移动12,进入
{
字符:

In [75]: ' '.join([chr(x) for x in range(111,130)])
Out[75]: 'o p q r s t u v w x y z { | } ~ \x7f \x80 \x81'
          ^ 1 2 3 4 5 6 7 8 9 ...12
因此,您得到不正确输出的原因是因为您的公式

code = chr(ord(letters) + shift)
没有考虑如果移位将您从与
a-z
a-z
相关的ord中跳出会发生什么情况(请注意
a-z
a-z
的ord范围也不是连续的!)


以下是有关如何修复的提示:

In [82]: alphabet = string.ascii_lowercase + string.ascii_uppercase

In [83]: alphabet.index('o')
Out[83]: 14

In [84]: alphabet[alphabet.index('o')+12]
Out[84]: 'A'
但是

结果导致
索引器:字符串索引超出范围
。这是因为
len(字母表)
是52,并且

In [91]: alphabet.index('O')+12
Out[91]: 52
不知何故,我们需要52将其返回到0。您可以使用:


这将返回一个字典…您期望的输出都不是字典…@user1609625:这不难修复。尝试一下。我会使用类似于
的if-letter.islower():mapping[letter]=mapping[letter]。lower()
In [85]: alphabet[alphabet.index('O')+12]
In [91]: alphabet.index('O')+12
Out[91]: 52
In [92]: 52 % 52
Out[92]: 0