简体   繁体   English

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

[英]Trying to format data retrieved from sqlite3 database by removing certain strings. What is wrong with my code?

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()

The replace() methods do not seem to be working but the program is running. replace()方法似乎不起作用,但是程序正在运行。

You have two problems here: 您在这里有两个问题:

  1. Inside the for loop, you are applying the replace function on record instead of records . for循环中,您是在record而不是records上应用replace函数。

  2. The replace function returns a new string, which you are "throwing away" every time you call it. replace函数将返回一个新字符串,您每次调用该字符串都会将其“丢弃”。

The solution to both, is changing record.replace(...) to records = records.replace(...) . 两者的解决方案都是将record.replace(...)更改为records = records.replace(...) record.replace(...) records = records.replace(...)

BTW, for better readability, I would rename record to records and vice-versa... 顺便说一句,为了提高可读性,我将record重命名为records ,反之亦然。

Update: 更新:

You have a more basic problem, I believe, with record = str(studentRequest) . 我相信,您有一个更基本的问题,即record = str(studentRequest)

Here is how you should probably do it: 您可能应该这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM