I'm currently working through Automate the Boring Stuff with Python book and run into curious issue on chapter 7. When trying to execute the following code:
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != "-":
return False
for i in range(4, 7):
if not text(i).isdecimal():
return False
if text[7] != "-":
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
print("415-555-4242 is a phone number:")
print(isPhoneNumber("415-555-4242"))
print("Moshi moshi is a phone number:")
print(isPhoneNumber("Moshi moshi"))
I get the following error message:
Traceback (most recent call last):
File "automation.py", line 27, in <module>
print(isPhoneNumber("415-555-4242"))
File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
Switching the str.isdecimal() method for str.isdigit() method allows me to execute the code properly, but I would like to know why the isdecimal() method will not work?
2 Answers 2
The error has nothing to do with isdecimal(). You have a typo in how you extract the character from text. The
if not text(i).isdecimal():
should read
if not text[i].isdecimal():
(note the square brackets.)
2 Comments
File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
The typeError is on line 13, where you are calling a string object. Use [] not ()
'\d{3}-\d{3}-\d{4}'matches your kind of phone numbers.text(i).isdigit()would raise the same error. You must have fixed the () typo at the same time.