3 回答

TA贡献1836条经验 获得超5个赞
我假设您对我的回答不了解正则表达式,但是您可以执行类似的操作并编写一个函数来检查每个空格是否有效。
def validSpaceFormat(space):
if len(space) == 2:
if space[0].isalpha() and space[1].isdigit():
return True
return False
def chess(value1, value2):
if validSpaceFormat(value1) and validSpaceFormat(value2):
print("Input correct.")
else:
print("Input wrong.")
value1, value2 = input('values: ').split()
chess(value1, value2)
这是假设人们总是将动作输入为“X1 Y2”
isalpha()并且isdigit()只处理字符,所以你需要索引字符串中的每个字符来检查它是什么。

TA贡献1815条经验 获得超6个赞
import re
def chess(value1, value2):
regex = "^\d[a-h]$"
return all([re.match(regex, s) for s in (value1, value2)])
\d[a-h]将只匹配一位数字后跟“abcfefgh”中的一个字符。的^并$确保它仅匹配长度2. re.match(正则表达式,s)实施字符串返回None如果字符串s不匹配正则表达式

TA贡献1155条经验 获得超0个赞
检查input长度是否为 2 的简单方法。
if len(a) == 2:
if (a[0].isdigit() and a[1].isalpha()) or ((a[1].isdigit() and a[0].isalpha())):
print('yes')
else:
print('no')
添加回答
举报