python - 如何去除列表中的 unicode

标签 python unicode

我想从列表中删除 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/

相关文章:

python - Pillow 安装错误 : command 'gcc' failed with exit status 1

python - 解析文本文件中的键值对

Python 3 Windows 服务仅在 Debug模式下启动

java - vaadin中的一些粗体

r - 从字符串中删除 Unicode 替换字符

python - Numpy:差异黑白 A[:i][:j] 和 A[:i,:j]

python - django:添加用户弹出窗口。缺少字段(名字、姓氏)

url - 有什么方法可以避免为 IDN 域显示 "xn--"?

python - Pandas 混合值列到字符串

python - 如何让Python bs4在XML上正常工作?