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

Caesar-cypher: ord() function receives a string, says it receives an integer

我应该创建一个 Caesar-cypher 函数。建议我使用内置的 ord() 和 chr() 函数来帮助我做到这一点(来自我的课程使用的教科书)。这可能是也可能不是最好的方法(绝对不是我查到的),但这是他们希望你做的。

我的问题是,在 for 循环中,当我将占位符变量发送到 ord() 函数时,我得到一个错误,它期望长度为 1 的字符串,但接收到的却是一个整数。我在它之前放了一个打印函数,以确认变量 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 以外的整数也会出现此错误。公平地说,我不完全确定代码本身是否符合我的要求(我一直试图弄清楚这部分,如果这部分不正确,我看不出确保其余部分工作的意义)。

ordstring 作为参数并且 returns int:

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of 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'

请注意,上面没有处理 overflow/underflow 情况,其中 'a' 向左旋转或 'z' 向右旋转。