gpt4 book ai didi

python - 如何使用 python 从列表中选择特定项目并保存在新列表中

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:24 24 4
gpt4 key购买 nike

我正在用 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)

最佳答案

为什么不使用正则表达式:

import re

if re.match('\w{4} \d{4}\w{2}', ProductCode):
message = 'Next Product'
else:
message = 'Non-Standard Product Code'

这匹配 AbcD 1234Az(4 个字母数字、空格、4 个数字和 2 个字母数字)

因此,如果您只需要字母而不是字母数字,请将模式更改为:

[a-zA-Z]{4} \d{4}[a-zA-Z]{2}

关于python - 如何使用 python 从列表中选择特定项目并保存在新列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31049027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com