我正在尝试创建一个程序,将用户输入的5个字母的字符串转换为浮点数,使用存储在字典中的值来转换每个字母。这是我的代码:
kvalues = {"a":1.01, "b":1.02, "c":1.03, "d":1.04, "e":1.05, "f":1.06, "g":1.07, "h":1.08, "i":1.09, "j":1.10, "k":1.11, "l":1.12, "m":1.13, "n":1.14, "o":1.15, "p":1.16, "q":1.17, "r":1.18, "s":1.19, "t":1.20, "u":1.21, "v":1.22, "w":1.23, "x":1.24, "y":1.25, "z":1.26}
def convert_key(key):
#converts the key into a float using the values stored in kvalues
k1 = float(kvalues.get(key[0]))
k2 = float(kvalues.get(key[1]))
k3 = float(kvalues.get(key[2]))
k4 = float(kvalues.get(key[3]))
k5 = float(kvalues.get(key[4]))
print k1 + k2 + k3 + k4 + k5
convert_key(raw_input (Please enter a key:))
当我运行程序时,我收到此错误:“TypeError:'builtin_function_or_method'对象没有属性' getitem '”。真正令人困惑的部分是当我通过空闲shell运行代码时:
key = "koala"
kvalues = {"a":1.01, "b":1.02, "c":1.03, "d":1.04, "e":1.05, "f":1.06, "g":1.07, "h":1.08, "i":1.09, "j":1.10, "k":1.11, "l":1.12, "m":1.13, "n":1.14, "o":1.15, "p":1.16, "q":1.17, "r":1.18, "s":1.19, "t":1.20, "u":1.21, "v":1.22, "w":1.23, "x":1.24, "y":1.25, "z":1.26}
k1 = float(kvalues.get(key[0]))
print k1
完美无缺!有谁知道这里的问题是什么?我是Python的新手,并不太熟悉语言的细微差别。
以下是完整的追溯:
Traceback (most recent call last):
File "K:\Projects\koala.py", line 73, in <module> menu()
File "K:\Projects\koala.py", line 10, in menu encrypt()
File "K:\Projects\koala.py", line 28, in encrypt e_key = convert_key(e_key)
File "K:\Projects\koala.py", line 67, in convert_key k1 = float(kvalues.get(key[0]))
TypeError: 'builtin_function_or_method' object has no attribute 'getitem'
将打印添加到功能的开头时:
<built-in method lower of str object at 0x0000000002AC7E40>
答案 0 :(得分:2)
问题在于你在做某件事:
e_key = mystring.lower
当你打算这样做时:
e_key = mystring.lower()
.lower
是一个方法,这意味着它需要像函数一样被调用,所以你需要括号。在第一种方法中,您只需将方法重新分配给e_key
变量。