Convert a List of Strings to UTF-8 in Python

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]

2 FEEDBACKS

  1. Damien says:

    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 unicode
    sequence]

  2. 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

LEAVE A COMMENT

Additional comments powered by BackType