Basically I need to find a way to figure out a way to find the EXACT word in a string. All the information i have read online has only given me how to search for letters in
Break up the string into a list of strings with .split() then use the in operator.
This is much simpler than using regular expressions.
You can use the word-boundaries of regular expressions. Example:
import re
s = '98787This is correct'
for words in ['This is correct', 'This', 'is', 'correct']:
if re.search(r'\b' + words + r'\b', s):
print('{0} found'.format(words))
That yields:
is found
correct found
EDIT: For an exact match, replace \b
assertions with ^
and $
to restrict the match to the begin and end of line.
Below is a solution without using regular expressions. The program searches for exact word in this case 'CASINO' and prints the sentence.
words_list = [ "The Learn Python Challenge Casino.", "They bought a car while at
the casino", "Casinoville" ]
search_string = 'CASINO'
def text_manipulation(words_list, search_string):
search_result = []
for sentence in words_list:
words = sentence.replace('.', '').replace(',', '').split(' ')
[search_result.append(sentence) for w in words if w.upper() ==
search_string]
print(search_result)
text_manipulation(words_list, search_string)
This will print the results - ['The Learn Python Challenge Casino.', 'They bought a car while at the casino']
I suspect that you are looking for the startswith()
function. This checks to see if the characters in a string match at the start of another string
"abcde".startswith("abc") -> true
"abcde".startswith("bcd") -> false
There is also the endswith()
function, for checking at the other end.
Actually, you should look for 'This is correct' string surrounded by word boundaries.
So
import re
if re.search(r'\bThis is correct\b', text):
print('correct')
should work for you.
You can make a few changes.
elif 'This is correct' in text[:len('This is correct')]:
or
elif ' This is correct ' in ' '+text+' ':
Both work. The latter is more flexible.