String python中的.find()函数是';行不通
我写这篇文章是为了测试python 2.7中的.find()函数,但它似乎不起作用。我的语法看起来不错,但我不明白为什么它不起作用String python中的.find()函数是';行不通,string,python-2.7,substring,String,Python 2.7,Substring,我写这篇文章是为了测试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?' 您需要使用s.count() 或s.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?'
您需要使用
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
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?'
您的布尔值和
.find()
的使用都是错误的
首先,如果你把
和放在一起'24'和'England'
你就得到了'England'
:
>>> '24' and 'England'
'England'
这是因为这两个字符串在Python意义上都是True
,因此最右边的字符串是和
的结果。因此,当您使用s.find('24'和'England')
时,您只需搜索'England'
.find()
返回子字符串---1
的索引,如果未找到,在Python意义上也是True
:
>>> bool(-1)
True
而.find()
可以为以目标字符串开头的字符串返回索引0
,但在布尔意义上,0
是False
。所以在这种情况下,您可能会错误地认为找不到字符串
在Python中测试存在性或成员资格测试的正确操作符是:
您可以用这种方式编写if
语句,或者更惯用地编写,以测试多个条件,在中使用all
(用于和)或任意(用于或):
>>> 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
然后,您可以在将来无缝地添加条件,而不是更改代码 '24'和'England'
表达式会给你一个布尔==False,这就是它要搜索的。那么我如何让它搜索这两个单词,并根据这些单词是否在里面打印一些东西呢?真的@PrestonM,投反对票?你能告诉我为什么吗?试试print('24'和'England')
。另外,你也不知道哪个用户否决了你。不,也不是我。在每个。。。指s.find('24')和s.find('England')。如果你想同时使用它们,你需要编辑你的答案,让它更清晰。特别是我提到的那一点。“24”和“英格兰”到底做了什么,以及他应该如何做。
>>> 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