TypeError: élément de séquence 0: chaîne attendue, int trouvé

202

J'essaye d'insérer des données d'un dictionnaire dans une base de données. Je souhaite parcourir les valeurs et les formater en conséquence, en fonction du type de données. Voici un extrait du code que j'utilise:

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

Lorsque j'exécute l'algo en utilisant des exemples de données (voir ci-dessous), j'obtiens l'erreur:

TypeError: élément de séquence 0: chaîne attendue, int trouvé

Un exemple de données value_list qui donne l'erreur ci-dessus est:

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] 

What am I doing wrong?

Homunculus Reticulli
la source
48
soulution for you: values = ",".join(map(str, value_list))
ddzialak

Réponses:

419

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

Use this generator expression instead :

values = ','.join(str(v) for v in value_list)
cval
la source
41
Can also use .join(map(str, value_list))
BallpointBen
49

Although the given list comprehension / generator expression answers are ok, I find this easier to read and understand:

values = ','.join(map(str, value_list))
kirpit
la source
2
Love this use of map and str. I will be using this pattern going forward :)
Timothy C. Quinn
18

Replace

values = ",".join(value_list)

with

values = ','.join([str(i) for i in value_list])

OR

values = ','.join(str(value_list)[1:-1])
Priyank Patel
la source
1
Another one values = ','.join(str(value_list)[1:-1])
Priyank Patel
4
remove the [,] from your second example, a list comprehension is not required and by removing them you have a generator which is more efficient.
jamylak
3
Actually, as explained at stackoverflow.com/questions/9060653/… , using a list instead of generator in the str.join() method is faster...
dtheodor
12

The answers by cval and Priyank Patel work great. However, be aware that some values could be unicode strings and therefore may cause the str to throw a UnicodeEncodeError error. In that case, replace the function str by the function unicode.

For example, assume the string Libië (Dutch for Libya), represented in Python as the unicode string u'Libi\xeb':

print str(u'Libi\xeb')

throws the following error:

Traceback (most recent call last):
  File "/Users/tomasz/Python/MA-CIW-Scriptie/RecreateTweets.py", line 21, in <module>
    print str(u'Libi\xeb')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 4: ordinal not in range(128)

The following line, however, will not throw an error:

print unicode(u'Libi\xeb') # prints Libië

So, replace:

values = ','.join([str(i) for i in value_list])

by

values = ','.join([unicode(i) for i in value_list])

to be safe.

Tomasz Nguyen
la source
1
This is the best solution here! values = ','.join([unicode(i) for i in value_list]) that works in case you have a mix of integers and strings with extended ascii characters.
mel
1
No longer an issue in Python3, str('\xeb') => ë
Brayoni
1

String interpolation is a nice way to pass in a formatted string.

values = ', '.join('$%s' % v for v in value_list)

Port Edison
la source
1

you can convert the integer dataframe into string first and then do the operation e.g.

df3['nID']=df3['nID'].astype(str)
grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))
Shaina Raza
la source