我想从列表中删除 unicode 字符串 例如 机场 [u'KATL',u'KCID']
预期输出
[KATL,KCID]
点击以下链接
Strip all the elements of a string list
尝试了其中一种解决方案
my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
map(str.strip, my_list) ['this', 'is', 'a', 'list', 'of', 'words']
出现以下错误
TypeError:描述符“strip”需要一个“str”对象但接收到一个“unicode”
最佳答案
首先,我强烈建议您切换到 Python 3,它将 Unicode 字符串视为一等公民(所有字符串都是 Unicode 字符串,但它们被称为 str
)。
但是如果你必须让它在 Python 2 中工作,你可以用 unicode.strip
去除 unicode
字符串(如果你的字符串是真正的 Unicode 字符串):
>>> lst = [u'KATL\n', u'KCID\n']
>>> map(unicode.strip, lst)
[u'KATL', u'KCID']
如果您的 unicode
字符串仅限于 ASCII 子集,您可以使用以下方法将它们转换为 str
:
>>> lst = [u'KATL', u'KCID']
>>> map(str, lst)
['KATL', 'KCID']
请注意,对于非 ASCII 字符串,此转换将失败。要将 Unicode 代码点编码为 str
(字节串),您必须选择编码算法(通常是 UTF-8)并在字符串上使用 .encode()
方法:
>>> lst = [u'KATL', u'KCID']
>>> map(lambda x: x.encode('utf-8'), lst)
['KATL', 'KCID']
关于python - 如何去除列表中的 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45353110/