【发布时间】:2017-06-17 15:25:16
【问题描述】:
我应该创建一个凯撒密码函数。建议我使用内置的 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 以外的整数也会出现此错误。公平地说,我不能完全确定代码本身是否符合我的要求(我一直试图弄清楚这部分,如果这部分没有,我看不出确保其余部分正常工作的意义)。
【问题讨论】:
-
不要使用
ord(num),只使用num:)
标签: python string function caesar-cipher