0

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)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
guul66
  • 9
  • 2

2 Answers2

0

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. You can use argument unpacking to avoid the issue entirely and make your code more legible:

prompt, expected = line.split('#')
expected = expected.rstrip()
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

You can use rstrip(), which, without arguments, will default to stripping any whitespace character. So just modify the conditional slightly, like this.

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