1

I wrote a simple class that takes an input zip or postal code and either returns that value or zero-pads it out to five digits if it happens to be all-numeric and less than 5 digits long.

Why doesn't my code work?

import re
class ZipOrPostalCode:
    def __init__(self, data):
        self.rawData = data
    def __repr__(self):
        if re.match(r"^\d{1,4}$", self.rawData):
            return self.rawData.format("%05d") 
        else:
            return self.rawData


if __name__ == "__main__":
    z=ZipOrPostalCode("2345")
    print(z)  

The output I expect is 02345. It outputs 2345.

Running it in the debugger, it is clear that the regular expression didn't match.

2
  • 1
    I think you misused the debugger, since the expression matches :) do like me (or Chuck Norris): I never use python debuggers, I just stare at the code until it confesses. Commented May 1, 2018 at 16:55
  • Probably. I couldn't make it recur. Thanks. Commented May 1, 2018 at 17:54

2 Answers 2

6

Your regex works, it's the format that doesn't because you're trying to pass an integer format for a string, and the other way round, and with old-style % syntax...

In str.format, the string object bears the format (using {} style syntax) and the strings/integers/whatever objects to format are passed as parameters.

Replace (for instance) by:

if re.match(r"^\d{1,4}$", self.rawData):
    return "{:05}".format(int(self.rawData))

without format, you can also use zfill to left-pad with zeroes (faster, since you don't have to convert to integer)

return self.rawData.zfill(5)

and you probably don't even need to test the number of digits, just zfill no matter what or only if the zipcode is only digits:

def __repr__(self):
   return self.rawData.zfill(5) if self.rawData.isdigit() else self.rawData
Sign up to request clarification or add additional context in comments.

2 Comments

Thank, I hadn't known about zfill()
it's little known, and usually not very useful since it only fills with zeroes. Just what you need, but that's a very special case!
3

You've got your format code backwards.

return "{:05d}".format(int(self.rawData))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.