简体   繁体   English

Python在文件中分割行时,最后将换行符保留

[英]Python when splitting line in file it leaves newline in the end

I'm trying to make a simple question/answer program, where the questions are written in a normal text file like this 我试图做一个简单的提问/回答程序,其问题都写在一个普通的文本文件中像这样

Problem is when i split the code (at the #) it also leaves the newline, meaning anyone using the program would have to add the newline to the answer. 问题是,当我分割代码(在#处)时,它也会离开换行符,这意味着使用该程序的任何人都必须将换行符添加到答案中。 Any way to remove that newline so only the answer is required? 有什么办法可以删除换行符,所以只需要答案?

Code: 码:

file1 = open("file1.txt", "r")
p = 0
for line in file:
    list = line.split("#")
    answer = input(list[0])
    if answer == list[1]:
        p = p + 1
print("points:",p)

Strip all the whitespace from the right side of your input: 从输入的右侧去除所有空格:

list[1] = list[1].rstrip()

Or just the newlines: 或者只是换行符:

list[1] = list[1].rstrip('\n')

Using list as a variable name is a bad idea because it shadows the built-in class name. 使用list作为变量名不是一个好主意,因为它遮盖了内置的类名。 You can use argument unpacking to avoid the issue entirely and make your code more legible: 您可以使用参数解压缩来完全避免问题,并使代码更清晰易懂:

prompt, expected = line.split('#')
expected = expected.rstrip()

You can use rstrip() , which, without arguments, will default to stripping any whitespace character. 您可以使用rstrip() ,它不带参数,默认情况下会剥离任何空白字符。 So just modify the conditional slightly, like this. 因此,只需像这样稍微修改条件即可。

if answer == list[1].rstrip():

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM