我对python中的索引感到困惑。我使用以下代码从文件中读取一行并打印列表中的第一项。我认为每次读取一行时索引都设置为零。我得到以下代码的索引超出范围。请解释我哪里出错了。
- (BOOL)isValidPhoneNumber:(NSString*)phoneNumber {
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:nil];
NSTextCheckingResult *result = [detector firstMatchInString:phoneNumber options:NSMatchingReportCompletion range:NSMakeRange(0, [phoneNumber length])];
if ([result resultType] == NSTextCheckingTypePhoneNumber) {
return YES;
}
return NO;
}
答案 0 :(得分:0)
如果字符串为空,则可能会变坏。
In [1]: line = ' '
In [2]: line = line.strip()
In [4]: b = line.split()
In [5]: b
Out[5]: []
In [6]: b[0]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-422167f1cdee> in <module>()
----> 1 b[0]
IndexError: list index out of range
或许更新您的代码如下:
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
line = line.strip()
b = line.split()
if b:
print(b[0])
答案 1 :(得分:0)
如果line
为空(换句话说它只包含空格和回车符),那么在line.strip()
之后它将是空字符串。
>>> line = ""
>>> line.split()[0]
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
line.split()[0]
IndexError: list index out of range
换句话说,当您对空字符串使用split
时,会返回一个空列表。所以没有元素零。
答案 2 :(得分:0)
如前所述,如果line为空,则会出现索引错误。
如果你想读行,可能会改变一些你的代码让Python为你做的工作
fname = input("Enter file name: ")
with open(fname) as f
lines = f.readlines()
# f will be closed at end of With statement no need to take care
for line in lines:
line = line.strip()
print(line)
# following line may not be used, as line is a String, just access as an array
#b = line.split()
print(line[0])