python - 如何使这段包含函数、for 和 while 循环的代码运行良好?

标签 python python-2.7

我正在制作一个基于文本的角色扮演游戏,但我在输入方面遇到了问题。我很难创建一个函数,该函数应该用关键字和一个项目将两个参数与字符串分开(例如:使用项目,获取项目...)但是,由于某种原因,它不断重复相同的操作等等。

我的代码:

def console(input):
        x = 0
        y = 0
        z = 0
        argument1 = ""
        argument2 = ""
        for x in input:
                if input != " " and y != 1:
                        argument1 += input
                elif y != 1:
                        y = 1
                else:
                        argument2 += input
        print argument1
        print argument2

console("use item")

运行代码时收到的输出是这样的:use itemuse itemuse itemuse itemuse itemuse itemuse itemuse item

我不知道为什么“use”和“item”在同一行,也不知道为什么它总共重复了八次。

最佳答案

split() 字符串方法已经完成了您想要做的事情:

>>> arg1, arg2 = 'use some item'.split(' ', 1)
>>> arg1
'use'
>>> arg2
'some item'

关于python - 如何使这段包含函数、for 和 while 循环的代码运行良好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9825301/

相关文章:

python - 如何使用python挂载网络目录?

python - Python:模糊图像中的特定区域

python - MongoKit "ImportError: No module named objectid "错误

python - 在 numpy 数组中迭代

python - 在 python 中的循环中编写循环的更简洁的方法

python - 枚举行为与 Python 之间的区别

python-2.7 - Jupyter notebook 只能在 python [root] 中运行

Python 结构体长度不正确

python - 如何仅从视频文件中获取第一个隐藏式字幕?

python - 在引号内使用引号