data_garden data_garden - 3 months ago 7
Python Question

Encountering problems encoding characters

I'm retrieving long lists of songs

ids
from
API
's, and I'm appending them to a list:

track_ids = [spotify:id:1,spotify:id:2 ...]


latetr on, song values are being passed to a function, in order to get corresponding song names, in this fashion:

(...)
for i, x in enumerate(values):
if x > threshold:
track_name = sp.track(track_ids[i])['name']
xsongs.append(track_name)
print product.upper(),'-', "{} = {}".format(track_name, x), filter_name


But when I run the script the list of song names output is halted showing the following error:

print product.upper(),'-', "{} = {}".format(track_name, x), filter_name
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 7: ordinal not in range(128)


EDIT:

the following line fixed it:

xsongs.append(track_name.encode("utf-8"))

Answer

You can encode every element of list. If your file system encoding is utf-8, you can try:

results = [value.encode('utf-8') for value in results]
print(results)
Comments