Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat string if condition, else do nothing

I want to concat few strings together, and add the last one only if a boolean condition is True. Like this (a, b and c are strings):

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

But Python does not like it. Is there a nice way to do it without the else option?

Thanks! :)

like image 525
lmaayanl Avatar asked Dec 29 '16 09:12

lmaayanl


4 Answers

Try something below without using else. It works by indexing empty string when condition False (0) and indexing string c when condition True (1)

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

I am not sure why you want to avoid using else, otherwise, the code below seems more readable:

something = a + b + (c if condition else '')
like image 198
Skycc Avatar answered Oct 23 '22 06:10

Skycc


This should work for simple scenarios -

something = ''.join([a, b, c if condition else ''])
like image 21
hspandher Avatar answered Oct 23 '22 08:10

hspandher


It is possible, but it's not very Pythonic:

something = a + b + c * condition

This will work because condition * False will return '', while condition * True will return original condition. However, You must be careful here, condition could also be 0 or 1, but any higher number or any literal will break the code.

like image 4
Fejs Avatar answered Oct 23 '22 06:10

Fejs


Is there a nice way to do it without the else option?

Well, yes:

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

But I don't know whether you mean literally without else, or without the whole if statement.

like image 1
Gwidryj Avatar answered Oct 23 '22 07:10

Gwidryj