如何用python分割线并获得剩余的线

时间:2019-04-07 08:18:57

标签: python

我的文件中有几行

0 1 2 3 4 5
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6

我正在尝试拆分行,但遇到错误,我想排除0 1并选择其余行,但是我如何使用python

elm1 = line.split()[0]
elm2 = line.split()[1]
elm3 = line.split()[2] +" "+ [3] +" "+ [4] +" "+ [5] +" "+ [6] +" "+ [7]

3 个答案:

答案 0 :(得分:2)

你是这个意思吗?

>>> line = "0 1 2 3 4 5 6 7"
>>> " ".join(line.split()[2:])
'2 3 4 5 6 7'

答案 1 :(得分:0)

我不明白您“选择其余行”是什么意思,但是要拆分行并排除01,您可以使用join()split()

line1 = '0 1 2 3 4 5'
line2 = '0 1 2 3 4 5 6 7'
line3 = '0 1 2 3 4 5 6'

filtered1 = ' '.join(num for num in line1.split() if num != '0' and num != '1')
filtered2 = ' '.join(num for num in line2.split() if num != '0' and num != '1')
filtered3 = ' '.join(num for num in line3.split() if num != '0' and num != '1')

print(filtered1)
print(filtered2)
print(filtered3)

输出

  

2 3 4 5

     

2 3 4 5 6 7

     

2 3 4 5 6

答案 2 :(得分:0)

您可以使用参数maxsplit

>>> s = "1 2 3 4 5 6 7 8"
>>> s.split(maxsplit=2)
['1', '2', '3 4 5 6 7 8']
>>> elm1,elm2,elm3 = tuple(s.split(maxsplit=2))