从文本文件中的整数中拆分字符串

时间:2015-03-18 20:59:47

标签: python-3.x

这是查看带有高分列表的文本文件并将它们放入列表的代码部分。我需要拆分字符串和整数。

OutList = input("Which class score would you like to view? ").upper()

if OutList == 'A':
    List = open("classA.txt").readlines()
    print (List)

elif OutList == 'B':
    List = open("classB.txt").readlines()
    print (List)

elif OutList == 'C':
    List = open("classC.txt").readlines()
    print (List)

此代码目前打印出来:

['Bobby 6\n', 'Thomas 4\n']

我需要知道如何将这些分开并摆脱' \ n'只打印出名称和分数。

1 个答案:

答案 0 :(得分:0)

使用rstrip()

以下是您修改过的程序:

OutList = input("Which class score would you like to view? ").upper()

if OutList == 'A':
    List = open("classA.txt").readlines()
    print (List)

elif OutList == 'B':
    List = open("classB.txt").readlines()
    print (List)

elif OutList == 'C':
    List = open("classC.txt").readlines()

for item in List:
    print(item.rstrip())

输出:

Which class score would you like to view? A
['Bobby 6\n', 'Thomas 4\n']
Bobby 6
Thomas 4

您可以阅读有关rstrip函数here的更多信息。

相关问题