Reputation: 4859
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.
Upvotes: 1
Views: 89
Reputation: 140178
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
Upvotes: 6
Reputation: 13750
You've got your format
code backwards.
return "{:05d}".format(int(self.rawData))
Upvotes: 3