问题描述
我刚刚写这个是为了测试 python 2.7 中的 .find() 函数,但它似乎不起作用.我的语法看起来不错,但我不知道为什么它不起作用.
s=raw_input('请说明关于你自己的两个事实')如果 s.find('24' 和 'England'):打印你是杰克威尔希尔吗?"别的:打印你是蒂埃里·亨利吗?"
你的布尔值和 .find()
的使用都是错误的.
首先,如果你和
一起'24'和'England'
,你就得到'England'
:
那是因为两个字符串在 Python 意义上都是 True
,所以最正确的是 和
的结果.因此,当您使用 s.find('24' and 'England')
时,您只是在搜索 'England'
.find()
返回子字符串的索引 -- -1
如果没有找到,这也是 Python 意义上的 True
:
并且 .find()
可以返回以目标字符串开头的字符串的索引 0
,在布尔意义上,0
> 是 False
.因此,在这种情况下,您会错误地认为未找到该字符串.
在 Python 中测试存在或成员资格测试的正确运算符是 in一个>:
>>>s='我 24 岁,住在英国'>>>s 中的24"和 s 中的英格兰"真的您可以以这种方式编写 if
语句,或者更惯用的方式来测试多个条件,请使用 all
(用于 and
)或 any
(用于 或
)与 in
:
然后您可以在未来无缝添加条件,而无需更改您的代码.
I've just written this to test out the .find() function in python 2.7 but it doesn't seem to work. My syntax looks right but i cant figure out why it's not working.
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?'
Your boolean and use of .find()
are both wrong.
First, if you and
together '24' and 'England'
you just get 'England'
:
>>> '24' and 'England'
'England'
That is because both strings are True
in a Python sense so the right most is the result from and
. So when you use s.find('24' and 'England')
you are only searching for 'England'
The .find()
returns the index of the substring -- -1
if not found which is also True
in a Python sense:
>>> bool(-1)
True
And .find()
could return the index 0
for a string that starts with the target string yet, in a boolean sense, 0
is False
. So in this case you would incorrectly think that string was not found.
The correct operator to test for presence or membership testing in Python is in:
>>> s='I am 24 and live in England'
>>> '24' in s and 'England' in s
True
You can write your if
statement that way, or more idiomatically, to test more than one condition, use all
(for and
) or any
(for or
) with 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
Then you can seamlessly add conditions in the future rather than change your code.
这篇关于python中的.find()函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!