Good day !
Based on the example below how could i print the word "fruits" ?
considering that it may change the position in the sentence and
considering that i have only "fr" as a search key
phrase = "I'm selling fruits and vegetables"
if "fr" in phrase:
...
How about:
phrase = "I'm selling fruits and vegetables"
phrase_lst = phrase.split()
for word in phrase_lst:
if word.startswith("fr"):
print(word)
There are several ways to do this. One is to use string find() method and then check where the next space is. Another way is to use regular expressions, which will be faster if you have a large text and you want to find all occurrences. You can also try if 'fr' in your_sentence
code in case you just want to check membership.
Example using re
import re
phrase = "I'm selling fruits and vegetables from France"
for match in re.finditer(r"([Ff]r\S*)", phrase):
print(match)
Output:
<re.Match object; span=(12, 18), match='fruits'>
<re.Match object; span=(34, 38), match='from'>
<re.Match object; span=(39, 45), match='France'>
If you only want the words.
import re
phrase = "I'm selling fruits and vegetables from France"
print(re.findall(r"([Ff]r\S*)", phrase))
Output:
['fruits', 'from', 'France']
re always confuses me!
re.search() finds the first instance of your match in phrase, so I tried re.search('fr(?=uits)', phrase) This will find fr if it is followed by uits:
import re
phrase = "I'm selling French fruit and vegetables from fruity France fruits"
# match fr followed by uits
m = re.search('fr(?=uits)', phrase)
m
Output:
<re.Match object; span=(59, 61), match='fr'>
phrase = "I'm selling French fruits and vegetables from fruity France fruits"
m = re.search('fr(?=uits)', phrase)
m
Output:
<re.Match object; span=(19, 21), match='fr'>
pos = m.span()
will get you the index positions of fr, like (19, 21) should you need them.