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

标签 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']

我该怎么做?

最佳答案

通过索引来打印列表中的唯一元素:

print(fixture[0])

输出:

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

或者,最好不要首先创建列表(注意缺少的 []):

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

How can I remove the "18:00" part from the output because all I need is "1,02/09/15, RNGesus, Ingsoc, Y, Ingsoc" (from comment)

现在,删除时间:

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

关于python - 如何打印列表的某些部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48081717/

相关文章:

python - 如何检查对象属性是否属于方法包装器类型?

Python 模块在导入语句中存在属性错误,即使导入语句在之前的代码中有效

Python3 - 将相似的字符串组合在一起

python - 如何在命令行中发送 python 文件执行的命令行参数?

python - 如何让子类使用父类的默认值?

python - 替换 Python 3.0 中的 htmllib 模块

python - Selenium/Python - 无法在用户名字段中输入文本

python-3.x - 使用之前训练好的模型在catboost中进行进一步预测

python - 如何向keras添加自定义指标? (平均绝对误差百分比)

python - 如何只重复列表中的某个元素?