我做了一个功能,需要在字符串中输入2个值。我正在努力使输入必须包含1位数字和1个字母的组合。示例:3f 5h我有以下代码,但我似乎无法使数字和alpha的条件工作。是因为.isdigit和.isalpha是关于所有角色的吗?
def chess(value1, value2):
if len(value1) == 2 and len(value2) == 2:
for char in value1, value2:
if char.isalpha() and char.isdigit():
print("Input is right format.")
else:
print("Input is NOT right format.")
else:
print("Input is NOT right format.")
value1, value2 = input('values: ') .split()
chess(value1, value2)
仅使用
if char.isalpha():
要么
if char.isdigit():
似乎工作。但他们在一起却没有。
我假设你对我的答案没有关于正则表达式的线索,但你可以做这样的事情并编写一个函数来检查每个空格是否有效。
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()
只对字符起作用,因此您需要索引字符串中的每个字符以检查它是什么。
BrightOne的回答就像一个魅力:
您可能可以使用正则表达式。现在,您可以执行value1 [0] .isalpha()和value1 [1] .isdigit(),依此类推。
检查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')
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的字符串。如果字符串s与正则表达式不匹配,则re.match(regex,s)返回None