Python: concat string if condition, otherwise do nothing

I want to combine several lines together and add the last only if the logical condition is True. Similarly (a, b and c are strings):

something = a + b + (c if <condition>)

But Python doesn't like it. Is there a good way to do this without the else option?

Thank!:)

+4
source share
4 answers

try something below without using it else, it works by indexing an empty string when the condition is False (0) and the indexing string cwhen the condition is True (1)

something = a + b + ['', c][condition]

I'm not sure why you want to avoid using else, otherwise the code below looks more readable

something = a + b + (c if condition else '')
+5
source

-

something = ''.join([a, b, c if condition else ''])
+3

, Pythonic:

something = a + b + c * condition

This will work because it condition * Falsewill return '', but condition * Truewill return the original condition. However, you have to be careful, conditionthere may also be 0or 1, but any larger number or any literal will break the code.

+1
source

Is there a good way to do this without the else option ?

Good, yes:

something = ''.join([a, b])
if condition:
    something = ''.join([something, c])

But I do not know if you literally mean without any changes, or without the expression all if.

0
source

Source: https://habr.com/ru/post/1665203/


All Articles