Python Forum
Searching for parts of a string or word
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Searching for parts of a string or word
#7
"in" works differently if you are comparing strings than if you are comparing a string to a list.

You are doing this:
"some" in ["This is awesome", "awesome"]
Used this way, "in" returns True if "some" == "This is awesome" or "some" == "awesome". Obviously neither is a match, so your code finds no match

The comparison is different if you use "in" to compare two strings.
"some" in "This is awesome"
This evaluates True because when comparing strings, "in" is looking for a substring in "This is awesome" that matches "some".

Neither of these comparisons are True if you enter "this is some tex". This is not a substring of "This is awesome" or "some".

I think what you want to do is break everything into words and compare the two sets of words. You could do this:
words  = "This is an awsome thing".split()

def search(text, words):
    """Return True if any word in text matches any part of a word in words"""
    for text in text.split():
        for word in words:
            if text in word:
                print(text, word)

search("This is a test of some thing", words)
This prints all the matching words which is more interesting than match/no match.

Another thing you can do is search for the longest common substring between to strings. This is one of those common homework problems that you can find solved a million times online.
Ulumulu likes this post
Reply


Messages In This Thread
RE: Searching for parts of a string or word - by deanhystad - Mar-15-2021, 03:10 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Exclamation A function that takes a word and a string of forbidden letters pooyan89 5 4,837 Jun-12-2019, 09:44 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020