简体   繁体   中英

Handling unexpected values in Python

I'm writing a piece of code to test if serial numbers have valid values and have proper formatting by comparing their various components against a list of known values. eg:

VALUES = [1, 2, 3, 4, 5]

serial = "013452345252345"

if int(serial[0:2]) in values:
    return True

In a valid case, the first two numbers can be treated as an int, but there are cases where the serial might come in as complete garbage, so I'm handling that and all valid cases by handling all my values as strings, eg:

VALUES = ['01', '02', '03', '04', '05']

serial = "a;alskdjfadslkj"

if serial[0:2] in values:
    return True

Is this the proper approach or is there something better or more intelligent I can do? Appreciate your help.

What you have done is what you should do. The only thing you are lacking at the moment is to cycle through the fields that you are checking (it is dependent upon a set field length though):

def Serial_Checker(values,serial,field_length):
    serial_length = len(serial)
    cycler = field_length

    serial_valid = True

    while cycler < serial_length:
        if serial[cycler-field_length:cycler] in VALUES:
            cycler += field_length     
        else:
            serial_valid = False
            break

    if serial_length%field_length <> 0: # % is the remainder operator
        serial_valid = False #In case there is leftover at the end of the serial

    return serial_valid

VALUES = ['01', '02', '03', '04', '05']
serial = "a;alskdjfadslkj"

Serial_Checker(VALUES,serial,2)

This should return a false from the function.

I don't know of any inbuilt function for this however if the format has to have all numbers you could always use the "isdigit" method:

d = 'somestring'
d.isdigit()

The last line will return a boolean if the string if the entire string is made of digits.

If you need a more general solution I can add more if you wish.

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