在python中扫描用户输入

时间:2013-04-01 23:00:18

标签: python

direction = input("enter a direction: ")
if direction != "quit" and direction != "go north" and direction != "go south" and direction != "go east" and direction != "go west" and direction != "go up" and direction != "go down" and direction != "look":
    print ("please enter in the following format, go (north,east,south,west,up,down)")

elif direction == "quit":
    print ("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh) ... the game should then end.")

elif direction == "look":
    print ("You see nothing but endless void stretching off in all directions ...")

else:
    print ("You wander of in the direction of " + direction)

我需要知道如何在python中执行此操作。 我需要先扫描用户输入2个字母 例如

i = user_input
#user inputs go ayisgfdygasdf

我需要它能够扫描用户输入,检查前2个字母是否已经去,如果它们已经去了但是它不识别第二个单词,在这种情况下是“ayisgfdygasdf”然后打印“抱歉,我不能这样做“

4 个答案:

答案 0 :(得分:1)

他也可以尝试使用:

    directions.split()

但在某些情况下可能需要使用try / except。

有关拆分和方法的更多信息,请尝试使用:

    dir(directions)

查看对象方向有哪些方法

或:

    help(directions.split) 

查看有关特定方法的帮助(在这种情况下,方法拆分对象方向)

答案 1 :(得分:0)

您可以使用[]表示法通过索引访问python中字符串的字符。您可以通过键入user_input [:2]来检查字符串中的前两个字符。此代码将包括所有字符,但不包括键入的索引。所以这个表示法将包括user_input [0]和user_input [1]。然后,您可以检查user_input [:2]是否等于'go',并从那里继续。

希望这会有所帮助。

答案 2 :(得分:0)

而是尝试使用:

direction = sys.stdin.readlines()

完成后可能需要你ctrl + D但你可以捕获更多。

此外,要获得子阵列,您甚至可以检查:

direction[:2] != "go"

或者,更可读的代码:

if not direction.startswith("go"):

另外,我建议,为了使您的代码更具可读性,

defined_direction = frozenset(["quit", "go north", "go south"])
if( direction not in defined_direction):
   print "please enter...."

答案 3 :(得分:0)

您可以为输入的各个字符编制索引:

if direction[:2] == "go":
    print "Sorry, I can't do that."

但是,尝试为每个可能的输入分配if-else分支通常是一个糟糕的选择...很难很快维护。

在这种情况下,更简洁的方法可能是定义具有有效输入的字典,如下所示:

input_response = {"quit":"OK ... but", "go north": "You wander off north", \
                  "go south": "You wander off south"} # etc

然后,您可以将代码重写为:

try:
    print input_response[direction]
except KeyError:
    if direction[:2] == "go":
        print "Sorry, I can't do that."
    else:
        print ("please enter in the following format...")
相关问题