我正在用Python(3)编写一个代码,检查产品代码的格式是否正确。代码作为变量输入,然后拆分为一个列表。我有两个问题。这些产品都是字母和数字,我想检查它们是否符合我规定的安排,应该是4个字母1个空格4个数字然后2个字母。你知道吗
下面的代码似乎可以工作,但在检查数据验证时,似乎.isdigit允许使用#或其他符号。你知道吗
我想做的更优雅,并尝试使用for循环来检查特定的项目是字母,例如[0,1,2,3,10,11],但不明白如何只检查列表中的这些特定项目
if (len(ProductCode) == 12 and
ProductCode [0].isalpha and
ProductCode [1].isalpha and
ProductCode [3].isalpha and
ProductCode [4].isalpha and
ProductCode [5]== ' ' and
ProductCode [6].isdigit and
ProductCode [7].isdigit and
ProductCode [8].isdigit and
ProductCode [9].isdigit and
ProductCode [10].isalpha and
ProductCode [11].isalpha):
message = 'Next Product'
else:
message = 'Non-Standard Product Code'
print(message)
为什么不使用正则表达式:
这与
AbcD 1234Az
(4个字母数字、空格、4个数字和2个字母数字)匹配因此,如果您只需要字母而不需要字母数字,请将模式更改为:
这只是一个例子,你可以循环通过你想要的列表,你可以把它应用到你的需要
相关问题 更多 >
编程相关推荐