result = ['袁惟仁', None, 'Life']
# Replace None with empty string
response = ['' if s is None else s for s in result]
# Handle non-ascii characters
return [s.encode('utf-8') if isinstance(s, unicode) else str(s) for s in response]
In this code I'm replacing None values of list with '', then I handle Unicode characters. This works fine, but want to know if there is a better way to do it. Right now if I don't handle empty I get an error saying can't convert None to str.
Same result you may get via using or
with list comprehension expression as:
>>> result = ['袁惟仁', None, 'Life']
>>> [r or '' for r in result]
['\xe8\xa2\x81\xe6\x83\x9f\xe4\xbb\x81', '', 'Life']
BTW, I don't get the part why you are explicitly doing .encode('utf-8')
.
filter(None, result)
will remove any None
s from the list:
filter(None, result)
['\xe8\xa2\x81\xe6\x83\x9f\xe4\xbb\x81', 'Life']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.