首页 > 解决方案 > 在 for 循环中组织 if 语句以从字符串中提取特定数据

问题描述

我有以下

items=' g energy 4"3/4 drilling jar'
print(items.split())
if 'energy' or 'ge' in items.split():
    print('E')
if 'slb' or 'schlumberger' in items.split():
    print('S')
if 'oes' or 'overseas' in items.split():
    print('O')

output 
E
S
O

我想要的是检查字符串中是否有任何单词但我得到的是它告诉我所有单词都在字符串中我想检查单词而不是单词的字符我怎么能去做到这一点?

标签: pythonif-statementdata-structures

解决方案


你对or的理解不太正确。

If we take one of you ifline:if 'slb' or 'schlumberger' in items.split()并使用 print 来评估其真实性

#you are essentially saying this
print(bool('slb'))
#or this
print(bool('schlumberger' in items.split()))

输出

True
False

所以你可以看到'slb'将返回true并'schlumberger' in items.split()返回false。

当您使用时,将首先评估or左侧的任何内容。or由于'slb'返回 true,or因此不会检查另一方,只会说这if是真的并打印您的信。

相反,您需要检查以 . 分隔的项目中的每个字符串or

items=' g energy 4"3/4 drilling jar'.split()
print(items)
if 'energy' in  items or 'ge' in items:
    print('E')
if 'slb' in items or 'schlumberger' in items:
    print('S')
if 'oes' in items or 'overseas' in items:
    print('O')

推荐阅读