什么是strpos的python等价物($ elem,“text”)!== false)

时间:2013-06-17 08:26:41

标签: php python-2.7 strpos

python相当于:

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

3 个答案:

答案 0 :(得分:31)

未找到时

返回-1:

pos = haystack.find(needle)
pos = haystack.find(needle, offset)
未找到时

引发ValueError:

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

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

needle in haystack

等同于以下PHP:

strpos(haystack, needle) !== FALSE

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

答案 1 :(得分:3)

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

答案 2 :(得分:0)

使用“in”:#/ p>,python是否非常漂亮

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))

最后2张打印也是如此,你选择。