1

The title sums it up really. I've got a string inside an array which is supposed to be for a multiple choice question game in a tutorial I'm following.

\n is to create a new line right? Look here.

When the tutor does it, and I'm absolutely copy/pasta his method, he gets line breaks, but me, no. I have the same version of python and am on Windows

question_prompts = [
"What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Black\n\n",
"What color are bananas?\n(a) Red\n(b) Pink\n(c) Yellow\n\n",
"What color are Strawberries?\n(a) Pink\n(b) Red\n(c) Yellow\n\n",
]
print(question_prompts)
  • Does this answer your question? ["\n" in strings not working](https://stackoverflow.com/questions/38401450/n-in-strings-not-working) – pkamb Oct 28 '21 at 23:25
  • The question_prompts[] are values for my questions class def __init__(self, prompt, answer). I use question_prompts as questions.prompt. – old_dog_newtricks Oct 29 '21 at 01:07

2 Answers2

2

Printing a list uses the elements' __repr__ method. For strings, this means "special characters" (read "control characters") are ignored (in other words, the strings' "raw" form is printed).

If you want \n to be printed while the strings are in a list, you have several options, two of which are:

  • Use str.join:

    print('\n'.join(question_prompts))
    
  • Use a loop:

    for question in question_prompts:
        print(question)
    
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

This also works.

question_prompts = [
"What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Black\n\n",
"What color are bananas?\n(a) Red\n(b) Pink\n(c) Yellow\n\n",
"What color are Strawberries?\n(a) Pink\n(b) Red\n(c) Yellow\n\n",
]
print(question_prompts[0])
print(question_prompts[1])
print(question_prompts[2])

And gives the output:

What color are apples?
(a) Red/Green
(b) Purple
(c) Black


What color are bananas?
(a) Red
(b) Pink
(c) Yellow


What color are Strawberries?
(a) Pink
(b) Red
(c) Yellow