Home > Net >  Why am I getting \\n within the strings that I import from a text file into a list?
Why am I getting \\n within the strings that I import from a text file into a list?

Time:10-07

I have a text file which contains the questions that I want to be asked in a quiz that I am trying to code in Python. I want these questions to appear as follows:

Multiple choice question?
(a) Option 1
(b) Option 2
(c) Option 3

As such, the question string is written out as follows:

"1. Multiple choice question?\n(a) Option 1\a(b) Option 2\n(c) Option 3\n\n"

These strings are stored in a text file, so that I can change them or add to them

I then use the following code to import these strings into a list in Python:

with open("questions.txt") as file_in:
    questions = []
    for question in file_in:
        questions.append(question)    

However, when I then:

print(questions)

I get:

['1. What is seven squared?\\n(a) 47\\n(b) 49\\n(c) 59\\n\\n\n', '2. What is the square root of 121?\\n(a) Nine\\n(b) Ten\\n(c) Eleven\\n\\n\n', '3. If a cube has a volume of 1000 cm^2, how long is each side?\\n(a) 6cm \\n(b) 8cm\\n(c) 10cm\\n\\n\n', '4. What is 347 minus 298?\\n(a) 59\\n(b) 49\\n(c) 69\\n\\n\n', '5. What is 22 x 11?\\n(a) 231\\n(b) 131\\n(c) 341\\n\\n\n']

i.e. extra \ characters have been added during the import, which means when I use these strings in my quiz, I see all of the \n code which is supposed to be formatting the question. I just want to import the strings exactly as they are in the text file, without the 'treatment' of \n resulting in

"\\n"

(two backslash ns)

CodePudding user response:

Firstly, read Why do backslashes appear twice? In short, Python uses backslashes to start escape sequences, so '\n' represents a newline and '\\' represents a backslash itself.


Now, I think the main problem here is conceptual. Reading a file is not the same as importing it. Reading means treating it as text, while importing means treating it as code.

I think the best solution here is a middle ground: structured data* like JSON or CSV. Here's how to do it in JSON:

questions.json

[
  "1. Multiple choice question?\n(a) Option 1\n(b) Option 2\n(c) Option 3\n\n"
]

tmp.py

import json

with open('questions.json') as f:
    questions = json.load(f)  # Parse JSON into data

print(questions)

Output

['1. Multiple choice question?\n(a) Option 1\n(b) Option 2\n(c) Option 3\n\n']

* I'm not sure this exactly the right term for it

CodePudding user response:

For a list named "questions", you can just do

questions = open("questions.txt").readlines()

  • Related