Caesar-cypher:ord()函数接收一个字符串,表示它接收一个整数

时间:2017-02-01 01:14:19

标签: python string function caesar-cipher

我应该创建一个Caesar-cypher函数。建议我使用内置的ord()和chr()函数来帮助我这样做(从我的课程使用的教科书)。这可能是也可能不是最好的方式(绝对不是我所看到的),但这是他们想要你做的。

我的问题是在for循环中,当我将占位符变量发送到ord()函数时,我得到一个错误,它期望一个长度为1的字符串,但是接收一个整数。我在它之前放了一个print函数来确认变量c在这种情况下的值是'i',但它似乎无论如何都会失败。

这是我创建的功能:

def rotate_word(word, num):
    count = 0
    newWord = ''
    while count < len(word):
        for c in word:
            print(c)
            newWord += chr(((ord(c)) - (ord(num) -1)))
            count += 1
    print(newWord)

这是我收到的错误:

rotate_word('ibm', -1)
i
Traceback (most recent call last):
  File "<pyshell#95>", line 1, in <module>
    rotate_word('ibm', -1)
  File "<pyshell#94>", line 7, in rotate_word
    newWord += chr(((ord(c)) - (ord(num) -1)))
TypeError: ord() expected string of length 1, but int found

对于-1以外的整数也会发生此错误。公平地说,我不完全确定代码本身是否符合我的要求(我一直试图弄清楚这一部分,并且如果这部分没有,我也没有看到确保其余部分工作的重点)。

1 个答案:

答案 0 :(得分:0)

ordstring作为参数并返回int

  

给定表示一个Unicode字符的字符串,返回表示该字符的Unicode代码点的整数。例如,ord(&#39; a&#39;)返回整数97和ord(&#39;€&#39;)(欧元符号)返回8364.这是chr()的反转。

在您的代码中,您传递了int,而不是您在命令行中看到的错误。您不需要将num转换为任何内容。只需将字符转换为数字,添加旋转量并使用chr将结果再次转换回字符:

def rotate_word(word, num):
    count = 0
    newWord = ''
    while count < len(word):
        for c in word:
            newWord += chr(ord(c) + num)
            count += 1
    print(newWord)

rotate_word('ibm', -1)  # 'hal'

请注意,上面没有处理向左旋转'a'或向右旋转'z'的溢出/下溢情况。