关于line.split命令的问题

时间:2011-07-28 14:07:41

标签: python split line

这是我需要处理的txt文件:

chr8    148401  153100  duplication

chr8    206001  207100  deletion

chr8    584401  589500  deletion

chr8    615101  616600  deletion

chr8    842601  843200  deletion

chr8    868901  869700  deletion

基本上我想提取两个数字,然后做减法。我的代码如下:

#!/usr/bin/python

import os,sys

file = open('/home/xxx/sge_jobs_output/rCEU.bed','r')
for line in file.readlines():
    num1 = line.split()[1].split()[0]
    num2 = line.split()[1].split()[1].split()[0]
    num = int(num2)-int(num1)
    print num

我可以成功打印出num1;但是num2不起作用。所以我们不能连续使用两个以上的.split?

错误就像:

Traceback (most recent call last):
  File "CNV_length_cal.py", line 8, in <module>
    num2 = line.split()[1].split()[1].split()[0]
IndexError: list index out of range

这里有什么问题?我对.split命令感到困惑......但是我找不到关于那个...的教程

1 个答案:

答案 0 :(得分:5)

一次拆分就足够了!

>>> s="chr8    584401  589500  deletion"
>>> l = s.split()
>>> l
['chr8', '584401', '589500', 'deletion']
>>> int(l[1]) - int(l[2])
-5099