Reputation: 27
I'm working through the book automating the boring stuff with python and came across this code he wrote to find phone numbers within a document.
The format of phone numbers is (12 characters): 123-456-7890
Why does the code check if length of text is 12? but doesn't python count from 0 and so it'll look for a length of 13?
Similarly, he wants to check if the first three digits are numbers but he uses a range(0, 3). Doesn't this check the first 4 digits including a hyphen which is not a number?
Thanks for the help.
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
Upvotes: 0
Views: 217
Reputation: 3782
You're getting list indexing, the len
function, and the range
function confused.
List indexing starts at 0 and increases for each element. The 13th element in a list is at index 12, and would be accessed with text[12]
.
The len
function, on the other hand, returns the actual length of the list. The length of a 2-element is, of course, 2, and that's what len
would return. In your example, the text is 13 characters long. len
returns 13, but the last index of the text would be at text[12]
.
The range
function is inclusive of the starting value and exclusive of the ending value. In your example of range(0, 3)
, it checks the items at locations 0, 1, and 2, not 0, 1, 2, and 3. If you want to check the first four numbers, use range(0, 4)
instead, which will check the elements at list indexes 0, 1, 2, and 3, which are also the first, second, third, and fourth elements in the string.
Upvotes: 0
Reputation: 171
The len
function returns the number of objects in a list.
i.e.
>>> len([1, 2, 3])
3
range(0, 3)
produces 0, 1, 2 and hence only checks the first three numbers.
>>> for i in range(0, 3):
... print(i)
...
0
1
2
Upvotes: 0
Reputation: 408
It's best to separate the concepts of indexes (the positions of objects in a list) and length (how many there are). Here's the doc of len(s) in Python.
range(start, stop) in Python includes the start and excludes the stop parameter. In mathematical notation, [start, stop). Therefore range(0,3) will check 0, 1, 2.
Upvotes: 0
Reputation: 26900
len()
returns the actual length of the string. Think of it, a string with length 0 (""
) also exists.
The last value of range(start, end)
is end-1
. The number 2 is in the range of 1-3
and the number 3 in the range of 3-5
. Inclusive bottom and exclusive upper bound.
Upvotes: 1