Python:TypeError:不支持的格式字符串传递给NoneType.__format__ [英] Python: TypeError: Unsupported format string passed to NoneType.__format__

查看:113
本文介绍了Python:TypeError:不支持的格式字符串传递给NoneType.__format__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前有一个程序从数据库中读取,可以在此处找到.我让用户选择他们想要显示的特定记录,以便SQL命令将执行该记录.现在,我有一个表,该表当前显示一些不包含任何NULL或空字符串的记录.如果它确实具有NULL或空字符串,则会给我一个错误,并且程序不会显示记录.我发现那是NoneType错误的主要来源.我不确定该如何解决.我如何确保它也可以计算Null或空字符串?希望可以解决该错误.

I have a program when it currently reads from a database, which can be found here. I have users choose a specific record they want to display so the SQL command will execute that record. Now I have a table that currently displays some records that do not include any NULL or empty strings. If it does have NULL or empty strings, it gives me an error and the program does not display the records. I figured that is where the NoneType error is mostly coming from. I'm not sure how to fix that. How can I make sure it also counts the Null or empty strings? Hopefully, that will fix the error.

如果要尝试测试数据库,则不会显示客户"之类的表,因为它具有空值.

If you were to try and test the DB, tables like Customers don't display because it has null values.

这是回溯错误:

line '..', in read_display(record)
    line = format_.format(*rec)
TypeError: unsupported format string passed to NoneType.__format__

这是我的代码的样子:

import sqlite3

def read_display(record):
  database = 'data.db'
  connection = sqlite3.connect(database)
  c = connection.cursor()
  sql = "SELECT * FROM {0}".format(record)
  cursor.execute(sql)
  conn.commit()
  results = cursor.fetchall()

  header = tuple(i[0] for i in c.description)
  width = max((len(str(x)) for d in data for x in d))

  data = [header] + results

  config = [{'width': 0} for _ in range(len(data[0]))]

  for rec in data:
    for c, value in enumerate(rec):
        config[c]['width'] = max(config[c]['width'], len(str(value)))


  format_ = []
  for f in config:
    format_.append('{:<' + str(f['width']) + '}')

  format_ = ' | '.join(format_)
  for rec in data:
    line = format_.format(*rec)
    print(line)

推荐答案

您在 line = format_.format(* rec)中有错误,并且在'{:s}'.format(None),所以看来 rec 的清单上有 None .

You have error in line = format_.format(*rec) and you can get the same error with '{:s}'.format(None) so it seems rec has None on list.

您必须使用 str(None)

您可以对 rec 中的所有元素使用 str()来确保:

You can use str() with all elements in rec to make sure:

 rec = [str(x) for x in rec]

所以代码应该是

for rec in data:
    rec = [str(x) for x in rec]
    line = format_.format(*rec)

这篇关于Python:TypeError:不支持的格式字符串传递给NoneType.__format__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆