简体   繁体   中英

A issue of concatenating two strings with if…else statement

I tried to concatenate two string like this

print 'AAA' if True else 'BBB' + 'CCC' if True else 'DDD'

In terminal, it just print like this 'AAA' but not 'AAACCC'. Why? Is there any other alternative way?

+ has a higher operator precedence than a conditional expression.

As a result, your expression is grouped like this:

('AAA') if (True) else (('BBB' + 'CCC') if (True) else ('DDD'))

You need to use parentheses to override the precedence:

print ('AAA' if True else 'BBB') + ('CCC' if True else 'DDD')

Demo:

>>> print 'AAA' if True else 'BBB' + 'CCC' if True else 'DDD'
AAA
>>> print 'AAA' if False else 'BBB' + 'CCC' if True else 'DDD'
BBBCCC
>>> print ('AAA' if True else 'BBB') + ('CCC' if True else 'DDD')
AAACCC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM