如何将字母字符串转换为整数?

3

具体而言,我正在处理用户输入的一个单词,该单词相当于一个数字(用户不知道该数字)。

我的代码:

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

不确定如何做..
6个回答

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
编辑: 正如 Ev. Kounis 在评论中提到的,您可以使用 get 函数,以便在用户输入不在字典中时获取默认值。
animals_map.get(animal, 0) # default for zero whether the user input is not a key at the dictionary.

2
你如何打字那么快... 我会使用更灵活的方式:animals_map.get(animal, 0) - Ma0
如果你是一名程序员,就学会打字:gtypist - Peter Wood
@Ev.Kounis,我同意使用get函数,我已经编辑了回答。谢谢! - omri_saadon
@omri_saadon 你也可以使用 defaultdict(int) - Peter Wood

2

请务必处理每一个输入值:

types = {'dog': 30, 'cat': 10, 'frog': 5}

def getInput():
  try:
    return 10 + types[raw_input("Give me an animal: ")]
  except:
    print("BAD! Available animals are: {}".format(", ".join(types.keys())))
    return getInput()

print(getInput())

你可以使用更有用的东西,比如可用的选项,而不是 pass,并将整个内容放入一个 while True 中,在 try 成功时使用 break,或许可以加上 else..请参考此链接 - Ma0
用户体验肯定可以得到提升。 - Vanojx1

1
animal = raw_input(>)
animal_dict = {'dog': 30, 'cat': 10, 'frog': 5}
number = animal_dict.get(animal, 0):
print 10+number

1
一个字典是最好的想法,就像其他人已经发布的那样。只是不要忘记处理错误的输入。
animals = dict(dog=30,cat=10,frog=5)
animal = raw_input(">") # and a user inputs cat
if animal in animals:
    print "animal %s id: %d" % (animal,animals[animal])
else:
    print "animal '%s' not found" % (animal,)

https://docs.python.org/2/tutorial/datastructures.html#dictionaries


0
你可以使用字典来完成这个任务:
animal = raw_input( > ) #and a user inputs cat

d = {'dog' : 30, 'cat' : 10, 'frog' : 5}

print 10 + d[animal]

-4

使用eval

print (10 + eval(animal))

对于您的情况,这可能是一个问题,但在创建更复杂的内容时,它可能会出现一些安全问题。参见:在Python中使用eval是不好的实践吗?

虽然在某些情况下生成代码可能很方便,正如评论中所指出的那样,请谨慎使用。

编辑:您可以使用更安全的版本,它只会评估字面表达式

import ast
print ( 10 + int(ast.literal_eval(  animal)))

1
使用eval来执行用户输入的字符串是非常糟糕的想法。这基本上允许用户执行任意代码。 - khelwood
这个解决方案虽然不是最佳实践,但对于这个任务来说是有效的,为什么要点踩呢? - Tbaki
1
因为这是错误的建议。 - khelwood
1
@AndrasDeak,好的谢谢,我不知道rm -f这个东西,刚在另一篇帖子中学到了一个更安全的字面等效方法。 - Tbaki
1
@AndrasDeak 感谢您抽出时间帮助他人进步。 :D - Tbaki
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接