4

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'
hernanavella
  • 5,462
  • 8
  • 47
  • 84
  • 2
    ''.join(list).replace(' ',',') – David Bern Nov 15 '17 at 20:42
  • 1
    Good work closing the question guys, now he has to read two other answers and combine them to achieve what he wants in a less-than-idiomatic fashion. **When did enforcing the rules become more important than teaching people?** I'm voting to reopen, there's a difference between keeping the site clean and a question witch hunt. – salezica Nov 15 '17 at 20:47
  • 1
    @slezica I dont think its about the rules in this case, more about what he is asking. there is a difference, but is it a witch hunt in this case? – David Bern Nov 15 '17 at 20:53
  • 3
    `(a, b, c, d, e)` is a tuple, not a list. Lists are in `[]`. – Barmar Nov 15 '17 at 21:08
  • I would suggest changing the title. Because the title question asks for combining non-empty list elements, whereas the body and the answers all talk about joining strings. What if `a` though `e` are lists or tuples, with `b` and `d` `=[]` or `=()`? – niak Feb 17 '22 at 16:43

4 Answers4

7

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.

salezica
  • 74,081
  • 25
  • 105
  • 166
  • 2
    Note, you can also just use the condition `if string`, so `','.join(string for string in lst if string)` works the same and is slightly more concise. – Engineero Nov 15 '17 at 21:01
  • 2
    "and this doesn't create a new in-memory list either" - no, [it totally does](https://github.com/python/cpython/blob/v3.6.3/Objects/unicodeobject.c#L9950), because `join` materializes the argument into a list so it can make two passes. – user2357112 Nov 15 '17 at 22:28
3

The shortest thing you can do is

','.join(filter(None, mytuple))

(I renamed list to mytuple in oder to not shadow the builtin list.)

timgeb
  • 76,762
  • 20
  • 123
  • 145
2

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
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

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.

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29