You can use regular expressions and the word boundary special character \b (highlight by me):
Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that
\bis defined as the boundary between\wand\W, so the precise set of characters deemed to be alphanumeric depends on the values of theUNICODEandLOCALEflags. Inside a character range,\brepresents the backspace character, for compatibility with Python’s string literals.
def string_found(string1, string2):
if re.search(r"\b" + re.escape(string1) + r"\b", string2):
return True
return False
Demo
If word boundaries are only whitespaces for you, you could also get away with pre- and appending whitespaces to your strings:
def string_found(string1, string2):
string1 = " " + string1.strip() + " "
string2 = " " + string2.strip() + " "
return string2.find(string1)
Answer from Felix Kling on Stack OverflowYou can use regular expressions and the word boundary special character \b (highlight by me):
Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that
\bis defined as the boundary between\wand\W, so the precise set of characters deemed to be alphanumeric depends on the values of theUNICODEandLOCALEflags. Inside a character range,\brepresents the backspace character, for compatibility with Python’s string literals.
def string_found(string1, string2):
if re.search(r"\b" + re.escape(string1) + r"\b", string2):
return True
return False
Demo
If word boundaries are only whitespaces for you, you could also get away with pre- and appending whitespaces to your strings:
def string_found(string1, string2):
string1 = " " + string1.strip() + " "
string2 = " " + string2.strip() + " "
return string2.find(string1)
The simplest and most pythonic way, I believe, is to break the strings down into individual words and scan for a match:
string = "My Name Is Josh"
substring = "Name"
for word in string.split():
if substring == word:
print("Match Found")
For a bonus, here's a oneliner:
any(substring == word for word in string.split())
Finding a word within a string and then getting the "outter" characters until a space
Python - Find words in string - Stack Overflow
How to search for exact whole word match
How to check for an exact word in a string?
data = "This is some reallyawesomedata. bye."
I know I can simply do an answer = data.find("awesome"), but I'm having trouble wrapping my head around what it would take to get the full set of outer characters till a "space", once that initial "awesome" was found.
essentially, I'm looking to search for the word "awesome" and then return "reallyawesomedata."
If you want to make sure that it counts a full word like is will only have one in this is even if there is an is in this, you can split, filter and count:
>>> s = 'this is a sentences that has is and is and is (4)'
>>> word = 'is'
>>> counter = len([x for x in s.split() if x == word])
>>> counter
4
However, if you just want count all occurrences of a substring, ie is would also match the is in this then:
>>> s = 'is this is'
>>> counter = len(s.split(word))-1
>>> counter
3
in other words, split the string at every occurrence of the word, then minus one to get the count.
Edit - JUST USE COUNT:
It's been a long day so I totally forgot but str has a built-in method for this str.count(substring) that does the same as my second answer but way more readable. Please consider using this method (and look at other people's answers for how to)
Use the beg argument for the .find method.
counter = 0
search_pos = 0
while True:
found = my_string.find(word, search_pos)
if found != -1: # find returns -1 when it's not found
#update counter and move search_pos to look for the next word
search_pos = found + len(word)
counter += 1
else:
#the word wasn't found
break
This is kinda a general purpose solution. Specifically for counting in a string you can just use my_string.count(word)
I have a simple python script that parses a text file and replaces certain text words with alternates. The problem is that I need an exact word match. For example if I replace all text of "red" with a substitution, say "green" then all occurrences of red will be replaced with green, but an occurrence of "redrum" will be replace with "greenrum" and that's not what I want, because all text is significant and I will replace "greenrum" with something else. Note that the script will work if the occurrences of greenrum come before reddrum, but I have no way to tell what order the text is in. The substitution method I use is s.replace()...
s = s.replace('red', 'green')
s = s.replace('red2', 'green2')I just need the first parameter to find exact whole word matches only.
I want to define a function f(sentence,word) which given some sentence 'x' will return true iff that sentence contains exactly the string 'y'.
For example, 'This is a sentence' and 'sentence', should return true but 'This is a sentence' and 'sent' should return false.
So currently I have:
if word in sentence:
return True
else: return false
Problem with this obviously it will return true even if the word appears within another word. How should I check for an exact word?
What is wrong with:
if word in mystring:
print('success')
if 'seek' in 'those who seek shall find':
print('Success!')
but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example, 'word' in 'swordsmith' is True. If you only want to match whole words, you ought to use regular expressions:
import re
def findWholeWord(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
findWholeWord('seek')('those who seek shall find') # -> <match object>
findWholeWord('word')('swordsmith') # -> None
As per @Amadan's comment,
It depends more on the interpretation of the question. Is the word "car" found in the sentence "I like your scarf"? Some people will say yes — there is "car" inside "scarf" — and for those people, your code works correctly.
For this, your code works perfectly fine.
a = input("Enter a sentence:")
w = input ("Enter a word to be found in the sentence:")
if w.lower() in a.lower():
print("It is present")
else:
print("It is not present")
Output:
Enter a sentence:I like your scarf
Enter a word to be found in the sentence:car
It is present
>>>
Some people will say no — "car" is not a word in that sentence — and they would judge your code as incorrect.
For this, use:
a = input("Enter a sentence:")
w = input ("Enter a word to be found in the sentence:")
if w.lower() in a.lower().split():
print("It is present")
else:
print("It is not present")
output:
Enter a sentence:I like your scarf
Enter a word to be found in the sentence:car
It is not present
This works perfectly. Since the input() treats everything as string, you can even check for special characters or words which have accented letters.
Split up the string into words then test for the substring in each of the words.
For word in s.split():
If q in word:
Print word
You could do this but there are like... 400 edge cases that will make this a problem.
text = "This is my text"
keywords = ["Lo"]
if len(set(text.split()).intersection(set(keywords))) > 0:
print("Yes")
I'm not sure if I 100% understand what you're trying in a full context but the code below gives the intended results for the example you gave, it returns True if any of the words in the words list are matched with any of the words in the string. Then simply print out the string if result of all is True.
string = 'Vet approved home made dog food'
words = ['dog', 'food']
res = all(word in string for word in words)
if res:
print(string)
else:
print('Words not found in string.')
You can traverse the string and see if the word you want is present.
In python, while handling with strings, you can use the find() function.
This will give the index of the first occurance of the word.
str="Vet approved home made dog food. If I'm searching for dog food"
print(str.find("food"))
This will return the first occurance.
A way more better way to approach would be using regular expressions.
You would have to import re module.
THe syntax is re.search(pattern, string, flags=0)
You can later use the group() function and then find out the occurances. import re
# Target String
target_string = "et approved home made dog food"
# find substring 'dog food'
result = re.search(r"dog food", target_string)
# Print matching substring
print(result.group())
I'm trying to find known words inside a string of scrambled letters. For example "reuonnoinfe" is "onefournine" scrambled. I have a method that is meant to breakdown the string as well as the spelling of the numbers, and look through the string for the characters that spell the word, if all are found, it returns true. But I'm trying to do this using the find() method but with no luck. I'm mostly trying rubber duck debugging here but also might just not be seeing something
word = "reuonnoinfe"
def find_spelling(arr) -> bool: # arr is chars spelling the number
found = True
for char in arr:
if word.find(char) :
print(char)
else:
found = False
return found
a = """
!
interface blah
a
ssid test1
v
ssid test2
v
ssid test3
"""
p = r'(?<=ssid )\S+' # non-whitespace character chunk after ssid
match = re.findall(p, a)
This will give you: ['test1', 'test2', 'test3']
Split your string based on your key, ssid and then after discarding the first partition, iterate over the remaining partitions accepting only the first word and discarding the rest.
>>> a = """
!
interface blah
a
ssid test1
v
ssid test2
v
ssid test3
"""
>>> [e.split(None, 1)[0] for e in a.split("ssid")[1:]]
['test1', 'test2', 'test3']
A similar regex solution would be
>>> re.findall("ssid\s+(\w+)", a)
['test1', 'test2', 'test3']