python中strpos($elem,"text") !== false)的等效函数是什么?


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

python中对应的是:

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

未找到时返回-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/

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

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