problem with string
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Thu Jul 21 21:11:24 EDT 2005
Tzanko Tzanev a écrit :
> hi :)
> I need some help for this script
> I have
please take care of indentation when posting code.
> --------------------
> cursor = conn.cursor()
> cursor.execute("select * from playlist limit 5")
> result = cursor.fetchall()
> # iterate through resultset
> playlist_txt = ''
> for record in result:
mp3id = record[0]
mp3_title = record[1]
mp3_artist = record[2]
playlist_txt += mp3id + mp3_title + mp3_artist
Err... what about:
print "<br />\n".join([" - ".join(record[:3]) for record in result])
or :
for record in result:
print "%s - %s - %s <br />" % tuple(record[:3])
Anyway, avoid string concatenation in loop, prefer appending to a list
and then str.join():
playlist = []
for record in result:
playlist.append(record[0] + record[1] + record[2])
print "\n".join(playlist)
Note that this is a very strange and complicated way to write:
print "\n".join([''.join(rec) for rec[:3] in result])
And, finally, if you just want to check what's in your resultset:
print result
> #print mp3id , " - ", mp3_title , ' - ', mp3_artist , "<br />"
> cursor.close()
> conn.close()
Since you're doing a fetchall(), you could (and should if you don't use
em again) free your resources as soon as you've retrieved the resultset:
cursor = conn.cursor()
cursor.execute("select * from playlist limit 5")
result = cursor.fetchall()
cursor.close()
conn.close()
# now use the resultset...
> ------------------
> #and want to print this out of "for record in result:"
> print playlist_txt
>
> #but there is an error in
> playlist_txt += mp3id + mp3_title + mp3_artist
Are we supposed to guess what the error is ? Sorry, I'm not psychic
enough. Please post the full traceback.
(wild guess: mp3id is an integer ?)
More information about the Python-list
mailing list