Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the python equivalent of:

if (strpos($elem,"text") !== false) {
    // do_something;  
}
like image 855
Cosco Tech Avatar asked Jun 17 '13 08:06

Cosco Tech


People also ask

What is the strpos () function used for?

The strpos() function finds the position of the first occurrence of a string inside another string.

What is the use of strlen () and strpos () function?

strpos() Function: This function helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-sensitive, which means that it treats upper-case and lower-case characters differently.

What is Stripos?

The stripos() function finds the position of the first occurrence of a string inside another string. Note: The stripos() function is case-insensitive. Note: This function is binary-safe. Related functions: strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)


2 Answers

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/

like image 199
xdazz Avatar answered Oct 04 '22 05:10

xdazz


if elem.find("text") != -1:
    do_something
like image 36
Javier Provecho Fernández Avatar answered Oct 04 '22 03:10

Javier Provecho Fernández