Convert a List of Strings to UTF-8 in Python
Tuesday, September 29th, 2009
If you’d like to learn more about programming, contact me for a one-on-one lesson.
1 2 3 | def utf8ify(list): '''Encode a list of strings in utf8''' return [item.encode('utf8') for item in list] |
Since lists are mutable, it is probably better to not return the list (so that it is clear that it is converted in place) or return an encoded copy like:
def utf8list(unicodesequence):
return [s.encode('utf8') for s in unicodesequence]
Very nice suggestion! I don't take that approach very often:
item.method() for item in list
I'm going to have to take that into consideration more often. Very pythonic :P