简体   繁体   中英

Find substring in string without white spaces

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM