0

Let's say I have the following list ['house', 'John', 'garden']and a string 'MynameisJohn'. Is there a way in Python to check if any of the words in the list are part of the string even when there are no white spaces? The goal would finally be to have a function which returns the words which are part of the string and maybe something that describes where in the string the words start. So something like this:

def function(list, string):
    returns [(word, position in the string)]

I tried some things but essentially nothing works because I don't know how to deal with the missing white spaces... The only method I could think of is checking if any sequence in the string corresponds to one of the words, the problem is I don't know how to implement something like that and it doesn't seem to be very efficient.

I found a question here on StackOverflow which deals with kind of the same problem, but since I have a concrete list to compare the string to, I shouldn't run into the same problem, right?

Sito
  • 494
  • 10
  • 29
  • 1
    Would you expect it to return true for the string `hohohousethechimney!` (Ho ho ho use the chimney!)? – Sayse Aug 01 '18 at 19:32
  • A solution could be to match letters of the word? Like if you're trying to find 'John' in the string then split the string into a list, and iterate until you find J, then check for o, h and n.. – zbys Aug 01 '18 at 19:32
  • Possible duplicate of [Check if multiple strings exist in another string](https://stackoverflow.com/questions/3389574/check-if-multiple-strings-exist-in-another-string) – Sayse Aug 01 '18 at 19:36

2 Answers2

2

An IDLE example:

>>> find = ['house', 'John', 'garden']
>>> s = 'MynameisJohn'
>>> results = [item for item in find if item in s]
>>> print( results )
[John]

Explanation:

[item for item in find if item in s] is a list comprehension.

For every item in the list named find, it checks if item in s. This will return True if item is any substring in s. If True, then that item will be in the results list.

Gigaflop
  • 390
  • 1
  • 13
1

For finding position of some string in other string, you can use str.index() method.

This function() accepts list and string and yield words that match and position of the word in the string:

def function(lst, s):
    for i in lst:
        if i not in s:
            continue
        yield i, s.index(i)


lst = ['house', 'John', 'garden']
s = 'MynameisJohn'

for word, position in function(lst, s):
    print(word, position)

Output:

John 8
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91