How to select specific items from a list using python and save to a new list

I am writing code in Python (3) that validates product code in a specific format. codes are entered as a variable and then split into a list. I have two questions. The products are letters and numbers and I want to check if they are in accordance with my prescribed agreement; it should be 4 letters 1 space and 4 numbers, then 2 letters.

The below code works, but when checking the data validation it appears that .isdigit allows # or other characters.

I want to make it more elegant and try and use a for loop to check for specific items like letters [0,1,2,3,10,11], but can't figure out how to check only those 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)

      

+3


source to share


2 answers


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, spaces, 4 digits and 2 alphanumeric numbers)



So, if you want letters instead of alphanumeric characters, change the template to:

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

      

+4


source


This is just an example of how you can scroll 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")

      

0


source







All Articles