Concat字符串if条件,否则什么也不做

lma*_*anl 9 python string if-statement concat

我想将几个字符串连接起来,并且只有在布尔条件为True时才添加最后一个字符串.像这样(a,b和c是字符串):

something = a + b + (c if <condition>)
Run Code Online (Sandbox Code Playgroud)

但Python并不喜欢它.没有else选项,有没有一个很好的方法呢?

谢谢!:)

Sky*_*ycc 10

在不使用的情况下尝试以下内容else,它通过在条件为False(0)时索引空字符串并c在条件为True(1)时索引字符串来工作

something = a + b + ['', c][condition]
Run Code Online (Sandbox Code Playgroud)

我不确定你为什么要避免使用else,否则,下面的代码似乎更具可读性

something = a + b + (c if condition else '')
Run Code Online (Sandbox Code Playgroud)


hsp*_*her 6

这应该适用于简单的场景 -

something = ''.join([a, b, c if condition else ''])
Run Code Online (Sandbox Code Playgroud)