如何将一串字母变成整数?

Mar*_*ıos 3 python python-2.7

具体来说,我正在说一个用户输入的字,相当于一个数字(用户不知道).

我的代码:

animal = raw_input( > )  #and a user inputs cat
dog = 30 
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20
Run Code Online (Sandbox Code Playgroud)

不知道怎么做..

omr*_*don 6

我会在这里使用字典

首先,使用相关值初始化字典.

其次,要求用户输入.

最后,以用户输入为键从地图中获取值.

animals_map = {"dog" : 30, "cat" : 10, "frog" : 5}

animal = raw_input('>') #and a user inputs cat
animal_number = animals_map[animal]

print 10 + int(animal_number) #with the hope that will output 20
Run Code Online (Sandbox Code Playgroud)

编辑:

作为Ev.Kounis在评论中提到您可以使用get函数,以便在用户输入不在字典中时可以获得默认值.

animals_map.get(animal, 0) # default for zero whether the user input is not a key at the dictionary.
Run Code Online (Sandbox Code Playgroud)

  • 你怎么快速键入...我会使用更灵活的:`animals_map.get(animal,0)` (2认同)