If I have a string "Mary had a little lamb" and a list of strings such as ["Mary", "Bob", "Steve"] how to use a loop to search this string for items in the list?

Member Avatar for masterofpuppets

hi try something like this:

s = "Mary had a little lamb"
myList = [ "Mary", "Bob", "Steve" ]

for item in myList:
    for word in s.split( " " ):
        if item == word:
            #do stuff if they are equal...

or alternatively

for item in myList:
    if item in s:
        #do stuff...

or alternatively ( with indexing )

splitString = s.split( " " )
for i in range( len( myList ) - 1 ):
    for j in range( len( splitString ) ):
        if myList[ i ] == splitString[ j ]:
            #do stuff...

hope this helps you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.