如何打印列表的某些部分?

时间:2018-01-03 16:52:00

标签: python python-3.x

这是我的代码:

def option_A():
 print("Pick a Fixture!")
 fixture_choice = int(input("Enter: "))

 file = open("firesideFixtures.txt", "r")
 fixture_number = file.readlines(fixture_choice)
 fixture = [linecache.getline("firesideFixtures.txt", fixture_choice)] 
 print(fixture)
 file.close()

我正在使用的文件的第一行是:

1,02/09/15,18:00,RNGesus,Ingsoc,Y,Ingsoc

预期结果是:

1, 02/09/15, RNGesus, Ingsoc, Y, Ingsoc

我得到的结果:

['1,02/09/15,18:00,RNGesus,Ingsoc,Y,Ingsoc\n']

我该怎么做?

1 个答案:

答案 0 :(得分:1)

通过索引编辑列表中唯一的元素:

print(fixture[0])

输出:

1,02/09/15,18:00,RNGesus,Ingsoc,Y,Ingsoc

或者,更好的是不要在第一个位置创建列表(注意缺少的[]):

fixture = linecache.getline("firesideFixtures.txt", fixture_choice) 
  

如何从输出中删除“18:00”部分因为我需要的是“1,02 / 09/15,RNGesus,Ingsoc,Y,Ingsoc”(来自评论)

现在,删除时间:

fixture = linecache.getline("firesideFixtures.txt", fixture_choice) 
parts = fixture.split(',')
res = ','.join(parts[:2] + parts[3:])
print(res)
print(fixture)

输出:

1,02/09/15,RNGesus,Ingsoc,Y,Ingsoc