I have this output
[u'JACK', u'', u'ROSE', u'', u'JANE']
I want to remove the unicode from each element of a list and join them into a single string like that:
Output:
['JACK ROSE JANE']
I have this output
[u'JACK', u'', u'ROSE', u'', u'JANE']
I want to remove the unicode from each element of a list and join them into a single string like that:
Output:
['JACK ROSE JANE']
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?
There are many ways to program it. I prefer this:
output = str(" ".join(filter(None,[u'JACK', u'', u'ROSE', u'', u'JANE'])))
If you need list:
output = [str(" ".join(filter(None,[u'JACK', u'', u'ROSE', u'', u'JANE'])))]
In Python 2, use the str
function to convert a unicode string to a normal string:
>>> unicodeString = u'stuff'
>>> normalString = str(unicodeString)
>>> print(unicodeString)
u'stuff'
>>> print(normalString)
'stuff'
>>> 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'
just for the sake of simplicity:
output = [' '.join([str(a) for a in [u'JACK', u'JANE', u'ROSE']])]
['JACK JANE ROSE']
tested in python2.7 and python3.5
By using None in the filter() call, it removes all falsy elements. already by @Andrey
a = [u'JACK', u'', u'ROSE', u'', u'JANE']
c = [str(' '.join(filter(None, a)))]
print (c)
or iterate and get only True items, the contra argument here is the possibility of the string operators, o.lower,o.upper.....
b = [' '.join([o for o in a if o])]
print (b)