use*_*116 2 python string-conversion
对于我的检查命令,因为我不想这样做:
def examine(Decision):
if Decision == "examine sword":
print sword.text
elif Decision == "examine gold":
print gold.text
elif Decision == "examine cake":
print cake.text
...
Run Code Online (Sandbox Code Playgroud)
对于我游戏中的每个项目.
所以我想将Decision字符串的第二个单词转换为变量,以便我可以使用类似的东西secondwordvar.text.
我尝试使用eval(),但是当我在一个单词命令中拼写错误时,我总是会出错.
错误
IndexError: list index out of range
但它正在起作用.
现在我的代码是这样的:
def exam(Decision):
try:
examlist = shlex.split(Decision)
useditem = eval(examlist[1])
print useditem.text
except NameError:
print "This doesn't exist"
Run Code Online (Sandbox Code Playgroud)
有没有人有一个想法,另一种选择,我怎么能以一种简单的方式编写该功能?
我可能还应该包括完整的游戏.你可以在这里找到它:http: //pastebin.com/VVDSxQ0g
在程序的某个地方,创建一个字典,将对象的名称映射到它所代表的变量.例如:
objects = {'sword': sword, 'gold': gold, 'cake': cake}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将examine()功能更改为以下内容:
def examine(Decision):
tokens = shlex.split(Decision)
if len(tokens) != 2 or tokens[0] != 'examine' or tokens[1] not in objects:
print "This doesn't exist"
else:
print objects[tokens[1]].text
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |