Python “需要一个字符,但找到长度为 # 的字符串”加密程序不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27126444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:27:46  来源:igfitidea点击:

'expected a character, but string of length # found' Encryption Program not working

pythonpython-3.xencryptionasciitypeerror

提问by Daniel Johnson

My code:

我的代码:

def Encryption(text):
   for I in text:
      string = ""
      ASCII = ord(text)
      Result = ASCII + Offset
      if Result > 126:
         Result -= 94
      else:
         Result = Result
      ResultASCII = chr(Result)
      string += ResultASCII

For my first piece of GCSE coursework, we had to make an encryption program. The final part that we have to make is the part that actually encrypts your message. I've used this code, however it comes up with an error of:

对于我的第一篇 GCSE 课程,我们必须制作一个加密程序。我们必须制作的最后一部分是实际加密您的消息的部分。我已经使用了这段代码,但是它出现了一个错误:

TypeError: ord() expected a character, but string of length # found

How do I get it to detect a string instead of just a character?

我如何让它检测一个字符串而不是一个字符?

采纳答案by Hackaholic

ordargument is not string, it must be single character:

ord参数不是字符串,它必须是单个字符:

>>> ord('a')
97

you can try something like this to loop over string:

你可以尝试这样的东西来循环字符串:

>>> a = 'hello'
>>> [ ord(x) for x in a ]
[104, 101, 108, 108, 111]

replace this :

替换这个:

ASCII = ord(text)

to this:

对此:

ASCII = ord(I)

回答by Vishnu Upadhyay

ord: (c)                                                                                                             │
│ ord(c) -> integer                                                                                                    │                                                                                                                     
│ Return the integer ordinal of a one-character string.    

>>> ord('ab')

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found

>>> ord('a')
97