简体   繁体   中英

how do I choose specific items from a list using python and save in a new list

I am writing a code in Python (3) that checks a product code is in a certain format. the codes are entered as a variable and then split into a list. I have two issues. The products are both letters and numbers and I wish to check they conform to my prescribed arrangement; it should be 4 letters 1 space and 4 numbers then 2 letters .

The code below seems to work but when checking data validation it appears that .isdigit allows # or other symbols.

I want to make more elegant and try and use a for loop to check specific items are letters eg [0,1,2,3,10,11] but cannot understand how to only check these specific items in the list

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)

Why not use a regular expression:

import re

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

This matches something like AbcD 1234Az (4 alphanumeric, space, 4 digits and 2 alphanumerics)

So if you only want letters instead of the alphanumerics, change the pattern to:

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

This is Just an example of how you can loop through the list you want, you can apply it to your needs

letters_list = [0,1,2,3,10,11]

def check_letter(ProductCode):
  global letters_list
  for l in letters_list:
    if not ProductCode[l].isalpha: return False
  return True

if check_letter(ProductCode): print("Everything in list is a letter") #define ProductCode 
else: print("Something is wrong")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM