如何剥离python

时间:2017-11-25 17:44:37

标签: python python-3.x

我正在为学校写一个测验代码。代码迭代文本文件并从中加载问题和答案。用户将选择难度来进行测验。答案的选项数量将根据难度而有所不同。我用逗号分隔了文本文件中的每个问题和可能的答案。

from random import shuffle

file = open("maths.txt" , "r")
for line in file:
    question = line.split(",")
    print(question[0])
    if difficulty in ("e", "E"):
        options = (question[1], question[2])

    if difficulty in ("m", "M"):
        options = (question[1], question[2], question[3])

    if difficulty in("h", "H"):
        options = (question[1], question[2], question[3], question[4])

    options = list(options)
    shuffle(options)
    print(options)

    answer = input("Please enter answer: ")

    if answer in (question[1]):
        print("Correct!")
    else:
        print("incorrect")
  file.close()

这是文本文件的一行: 问题1.什么是4 + 5?,9,10,20,11

第一个选项(问题[1])将始终是正确的答案,因此我想改组选项。使用此代码,选项将使用方括号,换行符和引号输出。有谁知道我怎么能脱掉这些?我试图使用:line.split(",").strip()然而这似乎什么都不做。谢谢

4 个答案:

答案 0 :(得分:3)

问题是您正在尝试打印list对象。相反,您应该打印每个选项。你可能会更好地打印一些格式:

for option_num, option in enumerate(options):
    print("{} - {}").format(option_num, option)

请阅读enumerateformat以了解到底发生了什么

答案 1 :(得分:2)

这样的东西?

from random import shuffle
def maths_questions():
  file = open("maths.txt" , "r")
  for line in file:
    question = line.strip().split(",") # every line in file contains newline. add str.strip() to remove it
    print(question[0])

    if difficulty in ("e","E"):
        options = [question[1],question[2]]
    elif difficulty in ("m","M"):
        options = [question[1],question[2],question[3]]
    elif difficulty in("h","H"):
        options = [question[1],question[2],question[3],question[4]]
    # why to create tuple and then convert to list? create list directly

    shuffle(options) #shuffle list
    print("Options: ", ", ".join(options)) # will print "Options: opt1, opt2, opt3" for M difficulty

    answer=input("Please enter answer: ")

    if answer in (question[1]):
            print("Correct!")
    else:
        print("Incorrect, please try again...")
  file.close()

Python docs

  

str.join(iterable)

     

返回一个字符串,该字符串是iterable中字符串的串联。如果iterable中存在任何非字符串值,则会引发TypeError,包括bytes对象。元素之间的分隔符是提供此方法的字符串。

答案 2 :(得分:1)

$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ('$_POST['submitIpB']')";

答案 3 :(得分:1)

要从字符串中删除字符,请使用.rstrip("put text to remove here")删除字符串右端的字符,并使用.lstrip("text to remove")删除字符串左侧的字符。