question 463 Secure Python · easy
Read the five-digit ZIP from a postcode field
The checkout form accepts a US postcode typed by the customer. The shipping provider's API takes only the five-digit ZIP. Accept the two US formats exactly, return the five-digit part, and return None for anything else, so a malformed value never reaches the API.
Function
zip5(text)Acceptsfive ASCII digits (
02139), or five digits, a hyphen and four digits (02139-4307)Returnsthe five-digit ZIP as text (
"02139" for both examples); None when spaces, letters, other digit scripts or anything extra make the text invalidExamples
callzip5('02139')returns'02139'
callzip5('02139-4307')returns'02139'
callzip5('2139')returnsNone
callzip5('02139-43')returnsNone