【发布时间】:2016-05-25 15:47:00
【问题描述】:
我想检查一个子字母,所以我写了这段代码(Python 2.7):
print text
if ('e' or 'E') in text:
text = "%s"%float(text)
print text
按照here的建议。
文本是一个变化的变量,目前它的值是:0E-7
但是这不起作用。 当我调试时,它会跳过 if 块。
为什么条件为假?
【问题讨论】:
标签: python
我想检查一个子字母,所以我写了这段代码(Python 2.7):
print text
if ('e' or 'E') in text:
text = "%s"%float(text)
print text
按照here的建议。
文本是一个变化的变量,目前它的值是:0E-7
但是这不起作用。 当我调试时,它会跳过 if 块。
为什么条件为假?
【问题讨论】:
标签: python
您的代码要问的是“('e' or 'E') 中的值是 text 吗?”当您评估('e' or 'E') 时,您会得到'e'。这是修复:
if ('e' in text) or ('E' in text):
【讨论】:
('e' or 'E') 的计算结果为 'e'。所以你正在测试if 'e' in text:,这不是真的,因为0E-7 中的E 是大写的。
您可以在此处以交互方式查看它:
>>> text = '0E-7' # note that E is uppercase
>>> ('e' or 'E') in text # why is this false?
False
>>> ('E' or 'e') in text # but true here?
True
>>> ('e' or 'E') # aha! 'or' returns the first truthy value
'e'
>>> 'e' in text.lower() # this fixes it
True
>>> any(c in text for c in 'eE') # another possible fix
True
>>> not set(text).isdisjoint('eE') # yet another way to do it
True
【讨论】:
or 接受第一个值,如果它是“真实的”
('e' or 'E') 是一个布尔表达式,它的计算结果为'e'。
我的建议是:
if any(char in text for char in ('e', 'E')):
# ...
【讨论】: