php 什么是 python 等价的 strpos($elem,"text") !== false)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17143267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:21:59  来源:igfitidea点击:

What is the python equivalent of strpos($elem,"text") !== false)

phppython-2.7strpos

提问by Cosco Tech

What is the python equivalent of:

什么是 python 等价物:

if (strpos($elem,"text") !== false) {
    // do_something;  
}

回答by xdazz

returns -1 when not found:

未找到时返回 -1:

pos = haystack.find(needle)
pos = haystack.find(needle, offset)

raises ValueError when not found:

未找到时引发 ValueError:

pos = haystack.index(needle)
pos = haystack.index(needle, offset)

To simply test if a substring is in a string, use:

要简单地测试子字符串是否在字符串中,请使用:

needle in haystack

which is equivalent to the following PHP:

这相当于以下 PHP:

strpos(haystack, needle) !== FALSE

From http://www.php2python.com/wiki/function.strpos/

来自http://www.php2python.com/wiki/function.strpos/

回答by Javier Provecho Fernández

if elem.find("text") != -1:
    do_something

回答by Pedro Castineiras

Is python is really pretty that code using "in":

python真的很漂亮,使用“in”的代码:

in_word = 'word'
sentence = 'I am a sentence that include word'
if in_word in sentence:
    print(sentence + 'include:' + word)
    print('%s include:%s' % (sentence, word))

last 2 prints do the same, you choose.

最后 2 个打印做同样的,你选择。