0

Writing a simple program that strips punctuation from a phone number and returns just the digits in a string:

number = Phone("(223) 456-7890")

print(number.number) ---> should return "2234567890"

The below code does this when '()' is added to the call, otherwise it gives a Bound Method error (understandable).

Issue is that the test suite wants it to return on number.number (no parens)

Checked the docs on this and various S.O. answers and have tried self.number = "" in the init method, then trying to load this variable with my results and return that, but that didn't seem to do anything. Any help would be appreciated thx

class Phone (object):

def __init__(self, phone_number):
    self.phone_number = phone_number
    #self.number = ""

def number(self):
    punctuation = ['\'', '+', '(', ')', '-', '.',',',' ']
    cpn = list(self.phone_number)
    [cpn.remove(item) for item in punctuation if item in cpn]
    self.number = ''.join(cpn)
    return self.number
user3763074
  • 343
  • 5
  • 15

1 Answers1

1

Make it a property:

class Phone (object):

    def __init__(self, phone_number):
        self.phone_number = phone_number
        #self.number = ""

    def get_area_code(self, phone_number):
        punctuation = ['\'', '+', '(', ')', '-', ' ']
        #output = ''
        #for char in phone_number:
        #    if char not in punctuation:
        #        output += char

        return phone_number

    @property
    def number(self):
        punctuation = ['\'', '+', '(', ')', '-', '.',',',' ']
        cpn = [item for item in self.phone_number if item not in punctuation]
        return ''.join(cpn)

number = Phone("(223) 456-7890")
print(number.number) 
# 2234567890

I have modified the end of the method (there would be some additional improvements to do), using a list comprehension for its side effects as you did is not recommended, and remove as you used it would only remove the first instance of every punctuation character.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50