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

3

17

What is the python equivalent of:

if (strpos($elem,"text") !== false) {
    // do_something;  
}
Earl answered 17/6, 2013 at 8:26 Comment(3)
#5320422Indiscreet
Thanks for your ninja quick response. However I recieve this error when using .find: AttributeError: 'list' object has no attribute 'find'Earl
is there a module i should import to use the .find syntaxEarl
S
40

returns -1 when not found:

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

raises ValueError when not found:

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:

strpos(haystack, needle) !== FALSE

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

Schlegel answered 17/6, 2013 at 8:30 Comment(2)
thank you for the solution. just to clarify i used if needle in haystack:Earl
I fell in love with needle in haystack. Coming from PHP, Python code is so human readable...Beaird
L
4
if elem.find("text") != -1:
    do_something
Lawana answered 17/6, 2013 at 8:39 Comment(3)
This is exactly what I am using. But i receive the following error:AttributeError: 'list' object has no attribute 'find'Earl
I think you are searching into a object, not into a string. If you want to search a string into a object(w/ strings), you should use a loop. Check this and update it to your code: if "this is string example....wow!!!".find("exam") != -1: print "works";Lancer
AttributeError: 'Response' object has no attribute 'find'Obturate
O
0

Is python is really pretty that code using "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.

Overtrade answered 20/7, 2016 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.