split() Error:list index out of range
split() Error:list index out of range
line = "2013/12/10@19:48:25"
datetime = line.split('@')
print datetime[1]
每当我的程序运行时,它都会出错。我不知道为什么。但每当我检查日期时间变量时,它包含这个 ['2013/12/10', '19:48:25] 这是正确的。但是我无法使用 datetime[1] 访问第二个元素,它给我一个索引越界错误,但我可以访问 datetime[0]。有人能告诉我我做错了什么吗?请帮助,我很困惑并且 运行 没有耐心。谢谢!
编辑:这是真正的代码
def setTimeStamp(line,newline):
line = line.replace("[" , "")
line = line.replace("]", "")
datetime = line.split('@')
print datetime[0] #this works fine
#output sample: 2013/12/14
print datetime[1] #this is getting an error
def main():
newline = ''
cg = open('log.lg','r')
for line in cg:
line = line.strip()
parsed_line = line.split(" ")
print parsed_line[0]
# output sample: [2013/12/14@08:45:13.296+0800]
setTimestamp(parsed_line[0], newline)]'
到目前为止,这就是我正在做的事情。在我弄清楚代码有什么问题后我会继续,这就是为什么程序现在看起来毫无意义。
代码本身似乎是正确的,但您可以添加几个 assert
以确保一切按预期进行。
line = "2013/12/10@19:48:25"
assert "@" in line # check that "@" is present there
datetime = line.split('@')
assert len(datetime) == 2 # check that there are 2 elements
print datetime[1] # then it's safe to take the second element
顺便说一句,使用不同的名称而不是 datetime
是合理的,以避免隐藏 datetime 模块名称引起的潜在问题。
对于那些仍在寻找答案或对我为什么会收到错误感到奇怪的人来说,这是因为日志文件的文件格式是 UNIX 文本文件格式。因此, python 解析器在解析时会与一些隐藏的特殊字符混淆。使用 linux 中的 'unix2dos ' 命令将日志文件从 unix 转换为 dos 后,我解决了这个问题。在此之后,我的解析器工作顺利。
line = "2013/12/10@19:48:25"
datetime = line.split('@')
print datetime[1]
每当我的程序运行时,它都会出错。我不知道为什么。但每当我检查日期时间变量时,它包含这个 ['2013/12/10', '19:48:25] 这是正确的。但是我无法使用 datetime[1] 访问第二个元素,它给我一个索引越界错误,但我可以访问 datetime[0]。有人能告诉我我做错了什么吗?请帮助,我很困惑并且 运行 没有耐心。谢谢!
编辑:这是真正的代码
def setTimeStamp(line,newline):
line = line.replace("[" , "")
line = line.replace("]", "")
datetime = line.split('@')
print datetime[0] #this works fine
#output sample: 2013/12/14
print datetime[1] #this is getting an error
def main():
newline = ''
cg = open('log.lg','r')
for line in cg:
line = line.strip()
parsed_line = line.split(" ")
print parsed_line[0]
# output sample: [2013/12/14@08:45:13.296+0800]
setTimestamp(parsed_line[0], newline)]'
到目前为止,这就是我正在做的事情。在我弄清楚代码有什么问题后我会继续,这就是为什么程序现在看起来毫无意义。
代码本身似乎是正确的,但您可以添加几个 assert
以确保一切按预期进行。
line = "2013/12/10@19:48:25"
assert "@" in line # check that "@" is present there
datetime = line.split('@')
assert len(datetime) == 2 # check that there are 2 elements
print datetime[1] # then it's safe to take the second element
顺便说一句,使用不同的名称而不是 datetime
是合理的,以避免隐藏 datetime 模块名称引起的潜在问题。
对于那些仍在寻找答案或对我为什么会收到错误感到奇怪的人来说,这是因为日志文件的文件格式是 UNIX 文本文件格式。因此, python 解析器在解析时会与一些隐藏的特殊字符混淆。使用 linux 中的 'unix2dos ' 命令将日志文件从 unix 转换为 dos 后,我解决了这个问题。在此之后,我的解析器工作顺利。