In: Computer Science
Python: How would I modify the class below that takes a string and returns an object holding a valid NANP phone number. I am asked to filll in the three methods listed, but underfined, below: __str__(), area_code(), and normalize(). My task is to clean up differently formatted telephone numbers by removing punctuation, such as '(', '-', and the like, and removing and the country code (1) if present. I am asked to start by stripping non-digits, and then see if the digits match the pattern. If asked to create a phone number that does not meet the pattern above, I should throw a ValueError with a string explaining the problem: too many or too few digits, or the wrong digits.
For example, the strings below
+1 (617) 495-4024
617-495-4024
1 617 495 4024
617.495.4024
should all produce an object that is printed as (617) 495-4024
ValueErrors
Each of the following strings should produce a ValueError exception.
+1 (617) 495-40247 has too many digits
(617) 495-402 has too few digits
+2 (617) 495-4024 has the wrong country code
(017) 495-4024 has an illegal area code
(617) 195-4024 has an illegal exchange code
class Phone:
"A Class defining valid Phone Numbers"
def __init__(self, raw):
"Create new instance"
self.number = self._normalize(raw)
def __str__(self) -> str:
"Create printable representation"
pass
def area_code(self) -> str:
"Return the area code"
pass
def _normalize(self, raw: str) -> str:
""""Take string presented and return string with digits
Throws a ValueError Exception if not a NANP number"""
pass
class Phone:
"A Class defining valid Phone Numbers"
def __init__(self, raw):
"Create new instance"
self.number = self._normalize(raw)
def __str__(self) -> str:
"Create printable representation"
# remove area code
if self.number[0] == '1':
return f'({self.number[1:4]}) {self.number[4:7]}-{self.number[7:]}'
return f'({self.number[0:3]}) {self.number[3:6]}-{self.number[6:]}'
pass
def area_code(self) -> str:
return str(self.number[0]) + str(self.number[1]) + str(self.number[2])
def _normalize(self, raw: str) -> str:
""""Take string presented and return string with digits
Throws a ValueError Exception if not a NANP number"""
# string to return
number = ""
for digit in raw:
if digit.isdigit():
number += digit
if number[0] == '1':
if len(number) > 11:
raise ValueError(raw)
elif len(number) > 10:
raise ValueError(raw)
return number
# testing
# For example, the strings below
try:
print(Phone("+1 (617) 495-4024"))
print(Phone("617-495-4024"))
print(Phone("1 617 495 4024"))
print(Phone("617.495.4024"))
# should all produce an object that is printed as (617) 495-4024
# following string should produce a ValueError exception.
print(Phone("+1 (617) 495-40247"))
except ValueError as raw:
print("error in ", raw)
pass
.
Screenshot:
Output:
.