Conditional concatenation of a list of strings with a condition
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
.
source to share
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 "])
source to share