python if in or的问题

需要判断 一个词 是否存在于 字符串1 或者 字符串2 该怎么写呀

if word in (str1 or str2): #这样写似乎是先判断str1 还是str2为真
    print .....
  
阅读 12.1k
4 个回答
if word in str1 or word in str2:
    pass

题主还需多加学习啊


另一个办法是

str_list = [str1, str2]
if any(word in s for s in str_list):
    pass

()优先级高,所以就先判断str1 or str2了;
如果str1 不为空, str1 or str2 的结果是 str1, 相当于判断 if word in str1;
如果str1 为空, str1 or str2 的结果是 str2, 相当于判断 if word in str2;
都不满足你的需求;
说了这么多废话,就是想让你把括号去掉:

if word in str1 or str2:
    print 'hello world'
if word in str1 or word in str2:
    print .....

#如果要判断的字符串过多可以这样写
lst = [str1, str2]
in_lst = [_ for _ in lst if word in _]
if len(in_lst) > 0:
    print .....

题主的写法是先计算(str1 or str2)的结果 -> bool值
而后判断 word in True 或者是 word in False
如果要按照题主的意思要这样写

if word in str1 or word in str2:
    dosothing
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题