python - 如何防止 "AttributeError: '函数'对象没有属性 ''”

标签 python function object attributeerror

我一直在开发一个旨在加密用户输入的消息的程序。有两种加密选项,第二个加密选项旨在使消息中的每个字符与字母表颠倒后的内容相同。当我输入消息时,出现错误“AttributeError: 'function' object has no attribute 'find'”。

elif option1 == 2:
  def alphabet():
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    'abcdefghijklmnopqrstuvwxyz'.reverse() == 'zyxwvutsrqponmlkjihgfedcba'
    'abcdefghijklmnopqrstuvwxyz' [::-1] == 'zyxwvutsrqponmlkjihgfedcba'
    message = raw_input('What message would you like to encrypt?')
  message = raw_input('What message would you like to encrypt?')
  for character in message:
    position = alphabet.find(character)
    newPosition = (position) % 26
    newCharacter = alphabet[newPosition]
    print(newCharacter)enter code here

我的结构与第一个选项的代码类似,运行时没有任何问题,并且我知道这个错误可能源于 def 语句,我不完全确定如何正确构建。

if option1 == 1:
  add = 13
message = raw_input('What message would you like to encrypt?')
  for character in message:
    if character in alphabet:
      position = alphabet.find(character)
      newPosition = (position + add) % 26
      newCharacter = alphabet[newPosition]
      print(newCharacter)

我知道这个网站上经常有人问这样的问题,但这些问题的答案对我没有帮助,因为我的编程经验很少。

最佳答案

您收到错误,因为字母表是函数内定义的变量。因此,它是一个局部变量,无法在该函数之外访问。

我很困惑为什么那里有一个函数。我将用包含按顺序排列的字符的变量替换 Alphabet 函数下的所有内容。

这段代码实际上有很多问题 - for 循环中的代码也有缺陷。这是我的解决方案,其附加好处是将编码消息打印为一个字符串而不是一堆字符,以及处理非字母数字字符。

elif option1 == 2:
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    message = input('What message would you like to encrypt?')
    encoded = []
    for character in message:
        if character.isalpha():
            encoded.append(alphabet[25-alphabet.find(character)])
        else:
            encoded.append(character)
    print(''.join(encoded))

关于python - 如何防止 "AttributeError: '函数'对象没有属性 ''”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47385940/

相关文章:

Python正则表达式匹配行中的第二个或第三个单词

Python 词表排列

javascript - 在存储多种数据类型的项目时访问数组元素的恒定时间

c++ - 错误 : control reaches end of non-void function [-Werror=return-type] } ^

javascript - D3.js 加载完成后缩放特定路径

c++ - 对象数组

python - 'int'对象不是可迭代的python暴力破解密码

c - 无法读取迷宫字符并将其放入二维数组

javascript - 如何将嵌套的对象数组转换为数组对象

php - 获取 protected 对象中的字符串