【问题标题】:'expected a character, but string of length # found' Encryption Program not working'期望一个字符,但找到长度为 # 的字符串' 加密程序不起作用
【发布时间】:2015-01-23 10:34:32
【问题描述】:

我的代码:

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

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

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

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

【问题讨论】:

    标签: python python-3.x encryption ascii typeerror


    【解决方案1】:

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

    >>> ord('a')
    97
    

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

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

    替换这个:

    ASCII = ord(text)
    

    到这里:

    ASCII = ord(I)
    

    【讨论】:

    • 谢谢,但我如何将它融入我的代码中?我尝试在 a 中为 x 执行 ASCII = ord(x) 但没有成功。
    • 对不起,如果我不清楚,这段代码是我的 GCSE 课程的一部分,它基本上是使用 ASCII 图表加密消息,然后给用户一个 8 字符的密钥,以便他们可以解密将来会。
    • 感谢您的帮助!现在工作正常!
    • @DanielJohnson 如果可行,您可以接受我的回答
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      相关资源
      最近更新 更多