您好,我有以下功能:
def width(input,output,attr):
import re
input = input.strip()
if re.search(attr, input):
k = input.find(attr)
for i in input:
if i == attr[0]:
j = k + len(attr)+1
while ((j <= len(input)) | (j != ' ') | (input[j+1] != "'")):
j = j + 1
#print j, output, input[j], len(input), k
output = output+input[j]
break
k = k + 1
return output
print width('a=\'100px\'','','a')
我总是得到以下错误:
Traceback (most recent call last):
File "table.py", line 45, in <module>
print width(split_attributes(w,'','<table.*?>'),'','width')
File "table.py", line 24, in width
while ((j <= len(input)) | (j != ' ') | (input[j+1] != "'")):
IndexError: string index out of range
我试着用or
代替|
,但它不起作用!
发布于 2011-08-24 12:35:13
while ((j <= len(input)) | (j != ' ') | (input[j+1] != "'")):
0)您应该使用or
。
1)您不应该使用input
作为变量名;它隐藏了一个内置函数。
2) j
为整数,不能等于' '
,测试无用。
3)当j == len(input)
时,j <= len(input)
会通过。字符串的长度不是字符串的有效索引;长度为N的字符串的索引范围是从0到(N - 1 ) (也可以使用从-1到-N的负数,从末尾开始计数)。当然,j+1
也不能工作。
4)我不知道你到底想做什么。你能用语言解释一下吗?如上所述,这不是一个很好的问题;让代码停止抛出异常并不意味着它更接近正常工作,也不意味着它更接近成为好的代码。
发布于 2011-08-24 09:13:04
看起来j+1
是一个大于或等于字符串长度(input
)的数字。确保构建while循环,使j < (len(input) - 1)
始终为真,这样就不会出现字符串索引超出范围的错误。
发布于 2011-08-24 09:14:20
如果是j >= len(input) - 1
,那么j+1
肯定是越界的。另外,使用or
而不是|
。
https://stackoverflow.com/questions/7169348
复制相似问题