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! :)
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 '')
This should work for simple scenarios -
something = ''.join([a, b, c if condition else ''])
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With