python - 如何读取包含括号中的坐标的用户输入

标签 python input

我正在制作一个非常简单的游戏,您可以在其中制作一个数字表并隐藏用户需要找到的炸弹。

这是代码:

import random
def game(rows, colums):   
    table = (rows * colums - 1) * [' '] + ['bomb']    
    random.shuffle(table)    
    while True:    
        position = input('Enter next position (x, y):')    
        bombposition = position.split()    
        if table[int(bombposition[0])*colums + int(bombposition[1])] == 'bomb':    
            print('you found the bomb!')    
            break    
        else:    
            print('no bomb at', position) 

错误:

game(1,0)    
Enter next position (x, y):>?    
(1,0)    
Traceback (most recent call last):    
  File "input", line 1, in <module>   
  File "input", line 8, in game    
ValueError: invalid literal for int() with base 10: '(1,0)' 

最佳答案

首先,split 默认使用空格,因此要在逗号上拆分,您需要 position.split(',')。尽管如此,如果您在 上拆分,您的 split 仍然会将 () 附加到您的字符串上,例如在您的情况 '(1''0)'。我建议也许使用正则表达式从您的输入中提取数字

import re

position = input('Enter next position (x, y):') 
match = re.match(r'\((\d+)\, *(\d+)\)', position)
if match:
    x = int(match.group(1))
    y = int(match.group(2))
else:
    # input didn't match desired format of (x, y)

关于python - 如何读取包含括号中的坐标的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58236449/

相关文章:

javascript - 如何对输入标签中的两个数字求和?

捕获输入而不\n

python - Errno 10054 现有连接被远程主机强行关闭。 - 如何调试?

python - 解密 Hadoop Snappy 文件

python - django 1.8 在 CentOs 6.5 服务器上不工作

c++ - 为什么此代码不输出到文件?

python - 使用 python 将多个 JSON 文件插入 MongoDB

python - "Setting an array element with a sequence"numpy 错误

java - 使用箭头键

Java-芳香数字-输入