Concat string if condition, else do nothing

20,378

Solution 1

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 '')

Solution 2

This should work for simple scenarios -

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

Solution 3

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.

Solution 4

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.

Solution 5

a_list = ['apple', 'banana,orange', 'strawberry']
b_list = []

for i in a_list:
    for j in i.split(','):
        b_list.append(j)

print(b_list)
Share:
20,378
lmaayanl
Author by

lmaayanl

A proficient Full-stack developer, with passion to the startup lifecycle. Experienced in mentoring and making things happen. I want to utilize my skills to create a product that improves the world.

Updated on November 26, 2020

Comments

  • lmaayanl
    lmaayanl over 3 years

    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! :)

    • Wiktor Stribiżew
      Wiktor Stribiżew over 7 years
      Yeah, the condition will evaluate to either 1 or 0, and multiplication result will either give you the string or an empty string. See this demo. However, that is oh so obfuscated and not straight-forward, I'd rather refrain from using it unless you have to compress the code as much as possible (is it for code golf)?
    • lmaayanl
      lmaayanl over 7 years
      because people here tend to avoid the else if not needed, wanted to follow that guideline.