删除从文件中读取的列表中的换行符

Pyt*_*bie 35 python newline list

我有一个简单的程序,它带有一个ID号,并为匹配ID的人打印信息.信息存储在.dat文件中,每行一个ID号.

问题是我的程序也在从文件中读取换行符\n.我尝试了'name'.split()方法,但这似乎不适用于列表.

我的节目:

from time import localtime, strftime

files = open("grades.dat")
request = open("requests.dat", "w")
lists = files.readlines()
grades = []

for i in range(len(lists)):
    grades.append(lists[i].split(","))

cont = "y"

while cont == "y" or cont == "Y":
    answer = raw_input("Please enter the Student I.D. of whom you are looking: ")
    for i in range(len(grades)):
        if answer == grades[i][0]:
            print grades[i][1] + ", " + grades[i][2] + (" "*6) + grades[i][0] + (" "*6) + grades[i][3]
            time = strftime("%a, %b %d %Y %H:%M:%S", localtime())
            print time
            print "Exams - " + grades[i][11] + ", " + grades[i][12] + ", " + grades[i][13]
            print "Homework - " + grades[i][4] + ", " + grades[i][5] + ", " + grades[i][6] + ", " + grades[i][7] + ", " +grades[i][8] + ", " + grades[i][9] + ", " + grades[i][10]
            total = int(grades[i][4]) + int(grades[i][5]) + int(grades[i][6]) + int(grades[i][7]) + int(grades[i][8]) + int(grades[i][9]) + int(grades[i][10]) + int(grades[i][11]) + int(grades[i][12]) + int(grades[i][13])
            print "Total points earned - " + str(total)
            grade = float(total) / 550
            grade = grade * 100
            if grade >= 90:
                print "Grade: " + str(grade) + ", that is equal to an A."
            elif grade >= 80 and grade < 90:
                print "Grade: " + str('%.2f' %grade) + ", that is equal to a B."
            elif grade >= 70 and grade < 80:
                print "Grade: " + str('%.2f' %grade) + ", that is equal to a C."
            elif grade >= 60 and grade < 70:
                print "Grade: " + str('%.2f' %grade) + ", that is equal to a D."
            else:
                print "Grade: " + str('%.2f' %grade) + ", that is equal to an F."
            request.write(grades[i][0] + " " + grades[i][1] + ", " + grades [i][2] +
                          " " + time)
            request.write("\n")


    print
    cont = raw_input("Would you like to search again? ")

if cont != "y" or cont != "Y":
    print "Goodbye."
Run Code Online (Sandbox Code Playgroud)

eph*_*ent 76

str.strip()返回一个字符串,其中删除了前导+尾部空格,.lstrip并且.rstrip仅分别用于前导和尾随.

grades.append(lists[i].rstrip('\n').split(','))
Run Code Online (Sandbox Code Playgroud)

  • `.rstrip('\ r \n')`或简单的`.rstrip()`,都会删除它们. (7认同)
  • 导入操作系统;endl = os.linesep; .strip(endl) 或 rstrip / lstrip ... 这样您就不必担心操作系统 :)。 (2认同)

Mic*_*zek 17

您可以使用该strip()函数删除尾随(和前导)空格; 传递一个参数将允许您指定哪个空格:

for i in range(len(lists)):
    grades.append(lists[i].strip('\n'))
Run Code Online (Sandbox Code Playgroud)

看起来您可以简化整个块,因为如果您的文件每行存储一个ID,grades则只需lists删除换行符:

之前

lists = files.readlines()
grades = []

for i in range(len(lists)):
    grades.append(lists[i].split(","))
Run Code Online (Sandbox Code Playgroud)

grades = [x.strip() for x in files.readlines()]
Run Code Online (Sandbox Code Playgroud)

(以上是列表理解)


最后,您可以直接遍历列表,而不是使用索引:

之前

for i in range(len(grades)):
    # do something with grades[i]
Run Code Online (Sandbox Code Playgroud)

for thisGrade in grades:
    # do something with thisGrade
Run Code Online (Sandbox Code Playgroud)

  • @John错误本身是微不足道的,几乎是评论存在的原因; 大多数人只会评论"注意`strip()`将删除所有空格,而不仅仅是换行符;你可能想要使用`strip('\n')`代替".我说"你可以使用strip()函数删除尾随(和前导)空格",你应该把''\n''传递给`strip()`你是对的,但是downvotes是完全的无益的答案(见downvote工具提示).我想如果你想要从根本上做出正确的答案,并帮助提问者,但有轻微的错误,这是你的选择 (3认同)

mar*_*eau 6

您实际上可以通过将整个文件作为单个长字符串读入内存来充分利用换行符,然后使用它们通过使用 stringsplitlines)方法将其拆分为成绩列表,默认情况下,在此过程中将其删除。

with open("grades.dat") as file:
    grades = [line.split(",") for line in file.read().splitlines()]
...
Run Code Online (Sandbox Code Playgroud)

  • @joemaller:除了稍微快一点之外,[`str.splitlines()`](https://docs.python.org/2/library/stdtypes.html?highlight=splitlines#str.splitlines) 方法使用[通用换行符](https://docs.python.org/2/glossary.html#term-universal-newlines) 分割行的方法,而 [`str.split('\n')`](https:/ /docs.python.org/2/library/stdtypes.html?highlight=str.split#str.split) 不会这样做,因此前者也更好,因为它与平台无关。 (2认同)