lmaayanl
lmaayanl

Reputation: 448

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

Upvotes: 21

Views: 34176

Answers (5)

Skycc
Skycc

Reputation: 3555

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

Upvotes: 29

Abhay Prakash
Abhay Prakash

Reputation: 81

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)

Upvotes: 1

Fejs
Fejs

Reputation: 2888

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.

Upvotes: 4

Gwidryj
Gwidryj

Reputation: 1035

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.

Upvotes: 1

hspandher
hspandher

Reputation: 16753

This should work for simple scenarios -

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

Upvotes: 7

Related Questions