【发布时间】:2022-08-20 03:10:42
【问题描述】:
我目前正在阅读 ATBSWP 并且在其中一章中作者编写了一个程序,该程序遍历每 12 个字符(块)以确定给定文本中是否有电话号码。
def is_phone_num(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
message = \'Call me at 415-555-1011 tomorrow.\'
for i in range(len(message)):
chunk = message[i:i+12]
if is_phone_num(chunk):
我的问题是这段代码工作得很好。当我运行这段代码时,我期望得到一个 IndexError: string index out of range BECAUSE length of message is 60,当 for 循环运行并且 z 达到 55(例如)然后 z+12 将超出消息长度的范围那么为什么我没有得到 IndexError: string index out of range 并且代码运行完美?
-
无法重播您的问题,请使用您的源代码。
-
请再试一次 我刚刚编辑过
标签: python