繁体   English   中英

将用户输入转换为小写-文字冒险游戏-Python 3

[英]Converting user input to lowercase - text adventure game - python 3

我为另一个简单的问题表示歉意,但我确实陷入了困境...我试图添加.lower()方法以将任何用户输入(无论是大写,小写还是组合)转换为小写。

我只是不知道要在哪里添加.lower()?

这是游戏的主要功能:

def main():

for turn in range(20, 0, -1):
    print("")
    describe()
    cmd = input("Enter your command " + str(turn) + "> ")
    if cmd == "quit":
        print("You gave in so easily :-(")
        break
    elif cmd.startswith("go "):
        where = cmd[3:]
        move_cmd(where)
        if state == "dead":
            print("you are dead")
        elif state == "outside":
            print("You jimmy the door open with the crowbar and escape to your freedom!")
            break
    elif cmd.startswith("take "):
        obj_name = cmd[5:]
        take_cmd(obj_name)
    else:
        print("I do not understand '" + cmd + "'.  Try go/take/quit")
print("Game over")


if __name__ == "__main__":
    main()

所以我认为这也是添加代码的代码行...但是它不起作用...

cmd = input("Enter your command " + str(turn) + "> ").lower() 

这行不通...我是否需要添加另一个循环或以某种方式更改代码行?

先感谢您。

任何字符串都是str类的实例。 因此,您可以在任何字符串上使用.lower()、. upper()等。 input()返回的类型是str。 因此,您需要在if语句上方,该语句首先检查命令是否已退出:cmd = cmd.lower()

您可能想查看python的教程标准库参考,以便查看示例并查看标准库和类型(如str!)所提供的内容。

解决方案:代替使用“ cmd = input(”输入命令“ + str(turn)+”>“)” ,请使用以下命令之一:

cmd = raw_input("Enter your command " + str(turn) + "> ")
cmd = cmd.lower()

使用的raw_input()而不是输入()说明

1)input()等效于eval(raw_input()),因此它将输入解析并评估为有效的Python表达式。

2)eval()将字符串解释为代码。 而且,如果您编写了任何无法解析的命令,它都会出错。

您正在尝试将输入设置为小写。 您需要将var“ cmd”设置为小写

cmd = input("Enter your command " + str(turn) + "> ")
cmd.lower()
...
if ...
n=int(input("enter the number of lines"));
line=[]
print "Enter the line sequence:";
for i in range(n):
    line.append(raw_input());
for j in range(n):
    print line[j].upper();

This is a way to accept the string sequence and convert them into uppercase , i hope this can solve your problem in simple way

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM