简体   繁体   English

你如何用 python 修复 - TypeError: must be str, nor int -?

[英]How do you fix with python - TypeError: must be str, nor int -?

def rotate(letter, key):
  new = ord(letter)
  new = chr(new) + key
  return new

new = rotate(" "," ")
print(new)

for some reason the code allows me to enter the message and key but then gives me the TypeError.出于某种原因,代码允许我输入消息和密钥,但随后给了我 TypeError。

new is the character code of letter . newletter的字符代码。 You should be adding to new before you convert it back to a character, not after.您应该将其转换回字符之前添加到new ,而不是之后。

new = chr(new + key)

If I am formatting your code correctly, I think that your code looks like the following:如果我正确格式化您的代码,我认为您的代码如下所示:

def rotate(letter, key):
    new = ord(letter)
    new = chr(new) + key
    return new

The ord function takes a letter and outputs the character code for that letter. ord函数接受一个字母并输出该字母的字符代码。 The chr function takes a character code and turns it back into a letter. chr函数接受一个字符代码并将其转换回一个字母。 What's happened is that you are adding key to the letter, not to the number and you can't do that.发生的事情是您正在向字母添加密钥,而不是数字,而您不能这样做。 I think that what you were expecting is that rather than having chr(new) + key you would have chr(new + key) .我认为你所期望的是,而不是有chr(new) + key你会有chr(new + key) So the code would look as follows:所以代码如下所示:

def rotate(letter, key):
    new = ord(letter)
    new = chr(new + key)
    return new

This can be done shorter as well by combining the chr , ord , and return .这也可以通过组合chrordreturn来缩短。

def rotate(letter, key):
    return chr(ord(letter) + key)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM