加入字符串列表并删除Unicode前缀

时间:2016-11-09 08:10:49

标签: python python-2.7 unicode

我有这个输出

[u'JACK', u'', u'ROSE', u'', u'JANE']

我想从列表的每个元素中删除unicode,并将它们连接成一个单独的字符串:

输出:

['JACK ROSE JANE']

6 个答案:

答案 0 :(得分:1)

Previous answers are perfect. Just to show you another way:

result = [str(' '.join(filter(None, [u'JACK', u'', u'ROSE', u'', u'JANE'])))]

That's how to do it in functional paradigm :) And it looks nice, huh?

Actually, you don't need to worry about 'u' prefix. It simply let's you(as a developer) know that string is represented as unicode. I've added "str" to hide it(convert to ascii string) but it doesn't really needed. Please check this answer: What does the 'u' symbol mean in front of string values?

答案 1 :(得分:1)

有很多方法可以对它进行编程。我更喜欢这个:

output = str(" ".join(filter(None,[u'JACK', u'', u'ROSE', u'', u'JANE'])))

如果您需要清单:

output = [str(" ".join(filter(None,[u'JACK', u'', u'ROSE', u'', u'JANE'])))]

答案 2 :(得分:-1)

在Python 2中,使用str函数将unicode字符串转换为普通字符串:

>>> unicodeString = u'stuff'
>>> normalString = str(unicodeString)
>>> print(unicodeString)
u'stuff'
>>> print(normalString)
'stuff'

答案 3 :(得分:-1)

>>> in_list = list(filter(lambda x: len(x)>0, [u'JACK', u'', u'ROSE', u'', u'JANE']))
>>> output = " ".join(in_list)                                                                   
>>> output
'JACK ROSE JANE'

答案 4 :(得分:-1)

仅为了简单起见:

position

在python2.7和python3.5中测试

答案 5 :(得分:-1)

通过在f​​ilter()调用中使用None,它会删除所有的falsy元素。已经是@Andrey

a = [u'JACK', u'', u'ROSE', u'', u'JANE']

c = [str(' '.join(filter(None, a)))]
print (c)

或迭代并只得到True项,这里的反对论证是字符串运算符的可能性,o.lower,o.upper .....

b = [' '.join([o for o in a if o])]
print (b)