Conditional concatenation of a list of strings with a condition

I would appreciate a more efficient way to conditionally combine a list.

This method works:

sentence = ['this ','is ','are ','a ','sentence']
string = ''
for i in sentence:
    if i != 'are ':
        string += i

      

+3


source to share


2 answers


You can use str.join

and remember the list :

sentence = ['this ','is ','are ','a ','sentence']
string = ''.join([i for i in sentence if i != 'are '])

      



And yes, I used list targeting. This is usually faster than a generator expression when used str.join

.

+8


source


You can filter are

and combine with "".join

for example

>>> "".join(item for item in sentence if item != "are ")

      

Here "".join

means that we attach the strings returned by the generator expression, without the fill character. If you have ",".join

, then all the elements will be connected with ,

.



In fact, it "".join

will be faster with a list than with a generator expression. So just convert your generator expression to a list with a list like this

>>> "".join([item for item in sentence if item != "are "])

      

+4


source







All Articles