我需要打印一些东西,只有当布尔变量设置为True。所以,在看完这个之后,我尝试了一个简单的例子:

>>> a = 100
>>> b = True
>>> print a if b
  File "<stdin>", line 1
    print a if b
             ^
SyntaxError: invalid syntax  

同样的,如果我写print a if b==True。

我错过了什么?


当前回答

因为2.5你可以使用C 's ' ' ?"三元条件运算符,语法为:

[on_true] if [expression] else [on_false]

所以你的例子很好,但你必须简单地添加其他,比如:

print a if b else ''

其他回答

你可以使用:

print (1==2 and "only if condition true" or "in case condition is false")

你还可以继续这样说:

print (1==2 and "aa" or ((2==3) and "bb" or "cc"))

现实世界的例子:

>>> print ("%d item%s found." % (count, (count!=1 and 's' or '')))
1 item found.
>>> count = 2
>>> print ("%d item%s found." % (count, (count!=1 and 's' or '')))
2 items found.

这可以通过字符串格式化来实现。它可以使用%符号以及.format()和f-strings(3.6新增)

print '%s' % (a if b else "")

or

print '{}'.format(a if b else "")

or

print(f'{a if b else ""}')

试试这个。这可能对你有帮助

a=100
b=True

if b:
   print a

如果你不想从__future__导入print_function,你可以这样做:

a = 100
b = True
print a if b else "",  # Note the comma!
print "see no new line"

打印:

100 see no new line

如果你不反对从__future__导入print_function,或者使用python 3或更高版本:

from __future__ import print_function
a = False
b = 100
print(b if a else "", end = "")

添加else是使代码语法正确所需要做的唯一更改,条件表达式需要else(“in line if else块”)

我没有像线程中其他人使用的那样使用None或0的原因是,使用None/0会导致程序在b为False的情况下打印None或打印0。

如果你想阅读这个主题,我已经包含了这个功能添加到Python的补丁的发布说明的链接。

上面的“模式”与PEP 308中显示的模式非常相似:

This syntax may seem strange and backwards; why does the condition go in the middle of the expression, and not in the front as in C's c ? x : y? The decision was checked by applying the new syntax to the modules in the standard library and seeing how the resulting code read. In many cases where a conditional expression is used, one value seems to be the 'common case' and one value is an 'exceptional case', used only on rarer occasions when the condition isn't met. The conditional syntax makes this pattern a bit more obvious: contents = ((doc + '\n') if doc else '')

所以我认为总的来说,这是一种合理的方法,但你不能否认它的简单性:

if logging: print data

你总是需要在内联if中使用else:

a = 1 if b else 0

但更简单的方法是a = int(b)