尝试通过删除某些字符串来格式化从sqlite3数据库中检索的数据。我的代码出了什么问题?

时间:2014-02-22 14:22:25

标签: python replace sqlite

c.execute("SELECT Date, BehaviourType, BehaviourDescription "+
          "FROM Student "+
          "WHERE Forename = :forename "+
            "AND Surname = surname "+
            "AND YearGroup = :yeargroup "+
            "AND FormNumber = :formnumber "+
            "AND Date BETWEEN :startdate AND :enddate",
          {"forename": forename,
           "surname": surname,
           "yeargroup": yeargroup,
           "formnumber": formnumber,
           "startdate": startdate,
           "enddate": enddate})

        studentRequest = c.fetchall()
        record = str(studentRequest)

    #write to file
        f = open('Student Report', 'w')
        f.write('Name: ' + name)
        f.write(' Form Number: ' + (yeargroup +'/'+ formnumber))
        for records in record:
            record.replace("u'", " ")
            record.replace("'", " ")
            record.replace("(", " ")
            record.replace(")", " ")
            f.write(str(records))
        f.close()

replace()方法似乎不起作用,但程序正在运行。

1 个答案:

答案 0 :(得分:1)

您有两个问题:

  1. for循环中,您正在replace而不是record上应用records功能。

  2. replace函数返回一个新字符串,每次调用它时都会“扔掉”。

  3. 两者的解决方案是将record.replace(...)更改为records = records.replace(...)

    BTW,为了更好的可读性,我会将record重命名为records,反之亦然......

    <强>更新

    我相信,record = str(studentRequest)会有更基本的问题。

    您应该如何做到这一点:

    studentRequests = c.fetchall()
    
    for studentRequest in studentRequests:
        record = str(studentRequest)
        record = record.replace("u'"," ")
        record = record.replace("'" ," ")
        record = record.replace("(" ," ")
        record = record.replace(")" ," ")
        f.write(record+"\n") # or "\r\n" if your program is running on Unix