【问题标题】:.find() function in python isn't workingpython中的.find()函数不起作用
【发布时间】:2017-02-18 03:08:35
【问题描述】:

我刚刚写了这个来测试 python 2.7 中的 .find() 函数,但它似乎不起作用。我的语法看起来不错,但我不知道为什么它不起作用。

s=raw_input('Please state two facts about yourself')

if s.find('24' and 'England'):
    print 'are you Jack Wilshere?'
else:
    print 'are you Thierry Henry?'

【问题讨论】:

  • '24' and 'England' 表达式会给你一个布尔值 == False,这就是它要搜索的内容。
  • 那么我如何让它搜索这两个词并根据这些词是否在其中打印一些东西?

标签: string python-2.7 substring


【解决方案1】:

您的布尔值和.find() 的使用都是错误的。

首先,如果你and 一起'24' and 'England' 你会得到'England'

>>> '24' and 'England'
'England'

这是因为两个字符串在 Python 意义上都是 True,所以最右边的是来自 and 的结果。因此,当您使用s.find('24' and 'England') 时,您只是在搜索'England'

.find() 返回子字符串的索引 -- -1 如果没有找到,在 Python 意义上也是 True

>>> bool(-1)
True

.find() 可以为以目标字符串开头的字符串返回索引0,但在布尔意义上,0False。因此,在这种情况下,您会错误地认为未找到该字符串。

在 Python 中测试存在或成员资格测试的正确运算符是 in

>>> s='I am 24 and live in England'
>>> '24' in s and 'England' in s
True

您可以用这种方式编写if 语句,或者更惯用的方式来测试多个条件,使用all(用于and)或any(用于or)和in

>>> all(e in s for e in ('24','England'))
True
>>> any(e in s for e in ('France','England'))
True
>>> all(e in s for e in ('France','England'))
False

然后您可以在将来无缝添加条件,而不是更改您的代码。

【讨论】:

    【解决方案2】:

    Find 不返回布尔值,它返回找到值的起始索引。如果找不到该值,则返回 -1。

    s=raw_input('Please state two facts about yourself')
    
    if s.find('24') >=0 and s.find ('England') >= 0:
        print 'are you Jack Wilshere?'
    else:
        print 'are you Thierry Henry?'
    

    https://www.tutorialspoint.com/python/string_find.htm

    【讨论】:

      【解决方案3】:

      您需要使用s.count()s.find() != -1::英格兰和 24

      if s.find('24' and 'England'):  # it's a number which is always true hence your code is failing
      

      【讨论】:

      • 说真的@PrestonM,投反对票?你能告诉我为什么吗?
      • 试试print('24' and 'England')。此外,您不知道哪个用户对您投了反对票。不,也不是我。
      • 在每个...上表示 s.find('24') 和 s.find('England')。如果想一起使用它们会说两者
      • 您需要编辑您的答案并使其更清晰。尤其是我提到的那一点。 '24' and 'England'完全做了什么,以及他应该如何完全做。
      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多