smokingpenguin
smokingpenguin

Reputation: 615

Python: TypeError: Unsupported format string passed to NoneType.__format__

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.

Here is the Traceback error:

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

This is what my code looks like:

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)

Upvotes: 6

Views: 45739

Answers (1)

furas
furas

Reputation: 142879

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 the list.

You would have to convert it to string with str(None)

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

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

So code should be

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

Upvotes: 12

Related Questions