Given:
a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
list = (a, b, c, d, e)
How can I get a string using all the non empty elements of the list ?
Desired output:
'aaa,ccc,eee'
Given:
a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
list = (a, b, c, d, e)
How can I get a string using all the non empty elements of the list ?
Desired output:
'aaa,ccc,eee'
Using a generator expression:
",".join(string for string in lst if len(string) > 0)
The ",".join()
part is using the join()
method of strings, which takes an iterable argument and outputs a new string that concatenates the items using ","
as delimiter.
The generator expression between parenthesis is being used to filter empty strings out of the list.
The original list doesn't change.
The shortest thing you can do is
','.join(filter(None, mytuple))
(I renamed list
to mytuple
in oder to not shadow the builtin list
.)
You can use a generator-expression
:
','.join(s for s in list if s)
which outputs
:
'aaa,ccc,eee'
Why?
This takes advantage of the fact that an empty
string
evaluates to False
.
This can be seen clearer through some examples:
>>> if "a":
... print("yes")
...
yes
>>> if " ":
... print("yes")
...
yes
>>> if "":
... print("yes")
...
>>>
So the generator
says: for each string
in list
, keep 'if string'
- i.e. if the string
is not empty.
We then finally use the str.join
method that will take each string
in the iterator
that is passed into it (here a generator
) and concatenate them together with whatever the str
is. So here we use a ','
as the string
to get the desired result.
A little example of this:
>>> ','.join(['abc', 'def', 'ghi'])
'abc,def,ghi'
**As a side note, you shouldn't name your variable
list
as it overrides the built-in list()
function:
>>> list((1, 2, 3))
[1, 2, 3]
>>> list = 1
>>> list((1, 2, 3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
You can try this one too:
a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
tup = (a, b, c, d, e)
res = ",".join(filter(lambda i: not i=='', tup))
print(res)
The output will be:
aaa,ccc,eee
It is also a good practice not to use list
as a variable name, as it is a reserved keyword from Python.