Reputation: 53
For example in a file) I like pineapple.
so I search "apple"
open(root_dir, encoding='UTF8').read().find("apple")
I want to get "pineapple". I mean full word.
How can I solve this problem?
Upvotes: 0
Views: 114
Reputation: 59
Regular expression is one of many programming choices you can use to solve this problem.
Let assume that we have 4 words: apple pineapple applepine pineapplepine. If you use the following pattern of regEx:
/\w*apple\w*/g -- You can match the whole word that contain a word “apple” in “apple” “pineapple” “applepine” and “pineapplepine”
/\w*apple/g -- You can match the whole word that contain a word “apple” in “apple” and “pineapple”
/apple\w*/g -- You can match the whole word that contain a word “apple” in “apple” and “applepine”
/apple/g -- You can match the whole word that contain a word “apple” in “apple” ONLY.
Upvotes: -1
Reputation: 5802
You can use a regular expression.
import re
result = re.findall(r'\w*apple\w*', # apple, surrounded by zero or more word symbols
'I got a pineapple, I got a pen.', # input string
re.I # optional: make search case insensitive
)
>>> result
['pineapple']
Upvotes: 4
Reputation: 4779
Convert that particular string to a list
using split()
, iterate over the list and Do a string match using in
.
lst = ['apple', 'pineapple', 'fruit', 'applephone']
for i in lst:
if 'apple' in i:
print(i)
apple
pineapple
applephone
Upvotes: 1