程序中两处有错误,请给出错误行的编号、错误的原因和改正后的整行代码。 import re telNumber = '''Suppose my Phone No. is 0535-1234567, yours is 010-12345678, his is 025-87654321.''' pattern = re.compile(r'(\d)-(\d{7,8})') index = 0 while True: matchResult = pattern.findall(telNumber, index) if not matchResult: break print('-'*30) print('Success:') for i in range(3): print('Searched content:', matchResult.group(i),\ ' Start from:', matchResult.start(i), 'End at:', matchResult.end(i),\ ' Its span is:', matchResult.span(i)) index = matchResult.end(2)
时间: 2023-12-30 13:04:18 浏览: 326
错误行的编号是第9行。原因是在print语句中使用了反斜杠续行,但是没有加上引号。应该修改为:
```python
print('Searched content:', matchResult.group(i), ' Start from:', matchResult.start(i), 'End at:', matchResult.end(i), ' Its span is:', matchResult.span(i))
```
另外,第7行应该将pattern.findall()的参数改为telNumber[index:],表示从telNumber的第index个字符开始查找。修改后的代码如下:
```python
import re
telNumber = '''Suppose my Phone No. is 0535-1234567, yours is 010-12345678, his is 025-87654321.'''
pattern = re.compile(r'(\d)-(\d{7,8})')
index = 0
while True:
matchResult = pattern.findall(telNumber[index:])
if not matchResult:
break
print('-'*30)
print('Success:')
for i in range(3):
print('Searched content:', matchResult[i][0]+'-'+matchResult[i][1], ' Start from:', matchResult[i].start(), 'End at:', matchResult[i].end(), ' Its span is:', (matchResult[i].start()+index, matchResult[i].end()+index))
index += matchResult[-1].end()
```
改正后的代码在输出结果方面也做了一些修改,使其符合预期。
阅读全文