微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从单个输入语句中分配多个值而忽略空格

如何解决从单个输入语句中分配多个值而忽略空格

我正在制作一个四连线游戏,其中棋盘大小可以由玩家决定,同时忽略数字之间的空格量。

inp = input("Please input the size of the board youd like with the number of rows before "
            "the number of columns. If you would like to quit,please type quit").split()
while inp != "quit":
    nRows,nCols = inp

这个方法以前对我有用,但它一直导致:

ValueError: not enough values to unpack

解决方法

您收到错误,因为您只传递了一个值作为输入。相反,你应该像

一样传递输入

1 2

input("msg").split() split 默认以空格为分隔符

所以你的代码是正确的,但你提供了错误的输入

,

我不知道我是否不明白你的问题,但在我看来你只能这样做:

    rRows = inp
    nCols = inp
,

当你按下回车键时,python 中的 input() 只返回一个值,所以试图用它创建两个值是行不通的。

您需要单独定义这些值,而不是在一个 input() 语句中。

rRows = input("enter the number of rows")
nCols = input("enter the number of columns")
,

字符串 split() 方法总是返回一个列表。因此,当用户输入一件事时,该列表只包含一项——这就是导致错误的原因。

在检查用户输入的 quit 时,您还需要考虑这些因素。下面的代码展示了如何处理这两种情况。

注意nRows 循环退出时,nColswhile 都将是字符串,而不是整数——或者如果用户输入 quit 甚至不存在{1}}。)

while True:
    inp = input('Please input the size of the board you\'d like with the number of rows '
                'before\nthe number of columns. If you would like to quit,please type '
                '"quit": ').split()

    if inp == ["quit"]:
        break
    if len(inp) != 2:
        print('Please enter two values separated by space!')
        continue
    nRows,nCols = inp
    break

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。