Python - 在测验列表中对问题和答案进行文字换行

Python - Textwrapping questions and answers in list within a quiz

我在 Python 中创建了多项选择测验。我想在保持多行格式的同时对问题和答案进行文本换行。尝试将下面的文本换行导致答案被合并或出现以下错误:“attributeerror 'list' object has no attribute 'expandtabs'”

import random
import time
import textwrap
class Question:
     def __init__(self, prompt, answer):
          self.prompt = prompt
          self.answer = answer
     
question_prompts = [
#Question 0
     "Question with so many words that not everything can fit on a single line, requiring a textwrap:\
     \na. Short answer\
     \nb. Medium answer\
     \nc. Answer with so many words that not everything can fit on a single line, requiring a textwrap\
     \nd. Answer\n",
#Question 1
     "What question is this?:\n\
     \na. Question 1\
     \nb. Completely irrelevant answer that is so long it cannot fit on a single line, requiring a textwrap\
     \nc. Not the right answer\
     \nd. Question 10\n"]

questions = [
     Question(question_prompts[0], "c"),
     Question(question_prompts[1], "b")]

def run_quiz(questions):
     score = 0
     start_time = time.time()
     end_time = time.time() - start_time
     minutes = end_time/60
     seconds = end_time % 60
     random.shuffle(questions)
     textwrap.fill(question, 30)
     for question in questions:
          response = input(question.prompt)
          correct = question.answer
          elapsed_time = time.time() - start_time
          if response == question.answer:
            print("Correct!\n")
            score += 1
          else:
              print("The correct answer is", correct, "\n")
     print("You scored", round(score/len(questions)*100, 1), "% correct")
     print("Quiz completed in", int(minutes), "minute(s) and", int(seconds), "second(s)")

run_quiz(questions)

您可以使用标准库的 textwrap 模块来做到这一点。

示例:

>>> import textwrap
>>> s = textwrap.fill("Question with so many words that not everything can fit on a single line, requiring a textwrap:")
>>> s
'Question with so many words that not everything can fit on a single\nline, requiring a textwrap:'
>>> print(s)
Question with so many words that not everything can fit on a single
line, requiring a textwrap:

默认行宽为 70 个字符,但您可以更改它。

对于字符串中间的长行,可以将字符串打断,将长的部分包起来,再拼接起来:

#Question 1
     "What question is this?:\n\
     \na. Question 1\n" +
     textwrap.fill("b. Completely irrelevant answer that is so long it cannot fit on a single line, requiring a textwrap") +
     "\nc. Not the right answer\
     \nd. Question 10\n"]

textwrap.fill 调用去除了长行上的初始换行符,因此我将其添加到前面字符串的末尾。

默认情况下,textwrap.fill 将在换行前用 space 个字符替换白色 space 个字符,包括换行符。如果您不希望它这样做,请将关键字参数传递给它 replace_whitespace=False.

默认情况下,textwrap.fill 还会在换行后删除每行开头和结尾的白色space。这似乎不适用于换行符,但包装文本末尾的换行符除外。如果您不希望它这样做,请将关键字参数传递给它 drop_whitespace=False.