我想从列表中删除unicode字符串,例如机场[u'KATL',u'KCID']
预期产出
[KATL,KCID]
按照以下链接
试过其中一个解决方案
my_list = ['this \n','是\n','a \n','list \n','\n','words \n']
map(str.strip,my_list)['this','is','a','list','of','words']
得到以下错误
TypeError:描述符'strip'需要'str'对象但收到'unicode'
ran*_*mir 10
首先,我强烈建议您切换到Python 3,它将Unicode字符串视为一等公民(所有字符串都是Unicode字符串,但它们被调用str).
但是如果你必须在Python 2中使它工作,你可以unicode使用unicode.strip(如果你的字符串是真正的Unicode字符串)剥离字符串:
>>> lst = [u'KATL\n', u'KCID\n']
>>> map(unicode.strip, lst)
[u'KATL', u'KCID']
Run Code Online (Sandbox Code Playgroud)
如果您的unicode字符串仅限于ASCII子集,则可以将它们转换为str:
>>> lst = [u'KATL', u'KCID']
>>> map(str, lst)
['KATL', 'KCID']
Run Code Online (Sandbox Code Playgroud)
请注意,对于非ASCII字符串,此转换将失败.要将Unicode代码点编码为str(字节串),您必须选择编码算法(通常为UTF-8)并.encode()在字符串上使用方法:
>>> lst = [u'KATL', u'KCID']
>>> map(lambda x: x.encode('utf-8'), lst)
['KATL', 'KCID']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10534 次 |
| 最近记录: |