Bootstrap FreeKB - Python (Scripting) - Find matching expression using find
Python (Scripting) - Find matching expression using find

Updated:   |  Python (Scripting) articles

find and re.match can be used to determine if a string or integer does or does not contain a match. find can be used if you do not want to include a regular expression, and re.match is used when you want to use a regular expression.

In this example, find should return 0, which indicates a match was found.

#!/usr/bin/python
foo = "Hello World"
print(foo.find('Hello'))

 

In this example, find should return -1, which indicates a match was not found.

#!/usr/bin/python
foo = "Hello World"
print foo.find('Goodbye')

 

Then an if statement can be used to do something when the result is or is not 0.

#!/usr/bin/python
foo = "Hello World"
if foo.find('Hello') == 0:
  print("The foo variable contains 'Hello'")
else:
  print("The foo variable does NOT contain 'Hello'")

 

Or like this, with find using -1.

#!/usr/bin/python
foo = "Hello World"
if foo.find('Hello') == -1:
  print("The foo variable does NOT contain 'Hello'")
else:
  print("The foo variable contains 'Hello'")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 23f590 in the box below so that we can be sure you are a human.