类型错误:序列项 0:预期的字符串,找到整数 [英] TypeError: sequence item 0: expected string, int found

查看:80
本文介绍了类型错误:序列项 0:预期的字符串,找到整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字典中的数据插入到数据库中.我想根据数据类型迭代这些值并相应地格式化它们.这是我正在使用的代码片段:

I am attempting to insert data from a dictionary into a database. I want to iterate over the values and format them accordingly, depending on the data type. Here is a snippet of the code I am using:

def _db_inserts(dbinfo):
    try:
        rows = dbinfo['datarows']

        for row in rows:
            field_names = ",".join(["'{0}'".format(x) for x in row.keys()])
            value_list = row.values()

            for pos, value in enumerate(value_list):
                if isinstance(value, str):
                    value_list[pos] = "'{0}'".format(value)
                elif isinstance(value, datetime):
                    value_list[pos] = "'{0}'".format(value.strftime('%Y-%m-%d'))

            values = ",".join(value_list)

            sql = "INSERT INTO table_foobar ({0}) VALUES ({1})".format(field_names, values)

    except Exception as e:
        print 'BARFED with msg:',e

当我使用一些示例数据(见下文)运行算法时,出现错误:

When I run the algo using some sample data (see below), I get the error:

类型错误:序列项 0:预期字符串,找到整数

TypeError: sequence item 0: expected string, int found

给出上述错误的 value_list 数据示例是:

An example of a value_list data which gives the above error is:

value_list = [377, -99999, -99999, 'f', -99999, -99999, -99999, 1108.0999999999999, 0, 'f', -99999, 0, 'f', -99999, 'f', -99999, 1108.0999999999999, -99999, 'f', -99999, 'f', -99999, 'f', 'f', 0, 1108.0999999999999, -99999, -99999, 'f', 'f', 'f', -99999, 'f', '1984-04-02', -99999, 'f', -99999, 'f', 1108.0999999999999] 

我做错了什么?

推荐答案

string.join 连接字符串列表中的元素,而不是整数.

string.join connects elements inside list of strings, not ints.

改用这个生成器表达式:

Use this generator expression instead :

values = ','.join(str(v) for v in value_list)

这篇关于类型错误:序列项 0:预期的字符串,找到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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