I have a string in which the word "LOCAL" occurs many times. I used the find()
function to search for this word but it returns another word "Locally" as well. How can I match the word "local" exactly?
The Exact String Match comparison is a simple comparison that determines whether or not two String/String Array values match. Use the Exact String Match comparison to find exact matches for 2 values for a String identifier.
Exact match (equality comparison): == , != As with numbers, the == operator determines if two strings are equal. If they are equal, True is returned; if they are not, False is returned. It is case-sensitive, and the same applies to comparisons by other operators and methods.
A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
For this kind of thing, regexps are very useful :
import re print(re.findall('\\blocal\\b', "Hello, locally local test local.")) // ['local', 'local']
\b means word boundary, basically. Can be space, punctuation, etc.
Edit for comment :
print(re.sub('\\blocal\\b', '*****', "Hello, LOCAL locally local test local.", flags=re.IGNORECASE)) // Hello, ***** locally ***** test *****.
You can remove flags=re.IGNORECASE if you don't want to ignore the case, obviously.
Below you can use simple function.
def find_word(text, search): result = re.findall('\\b'+search+'\\b', text, flags=re.IGNORECASE) if len(result)>0: return True else: return False
Using:
text = "Hello, LOCAL locally local test local." search = "local" if find_word(text, search): print "i Got it..." else: print ":("
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With