简体   繁体   中英

search a specific item of a list in a string python

I have two strings:

 a = "The quick brown fox did jump over a log"
 b = "The brown rabbit quickly did outjump the fox"

both of which have been converted into lists at each space. I want to make a for loop that takes each word one by one in list A and searches it in string B if it is found then the word gets added to a new string. Once the word is found, it deletes the entire first occurrence of the word in the second string. It is case sensitive, "the" is not the same as "The".I am confused about how to search for a specific word in a string and then delete it.

So first it would take the word from list A "The" and search for it in string B, since it is found the new string will consist of the word "The". Next word is quick, String B has quickly, the word Quickly contains quick, so then quick would be added to the new string.

The code I have so far:

a = "The quick brown fox did jump over a log"
b = "The brown rabbit quickly did outjump the fox"

import re

aa = re.sub("[^\w]", " ",  a).split()
bb = re.sub("[^\w]", " ",  b).split()
for aa[0] in range(b):

If I were to search every word in List A to string B, I would get "The quick brown fox did jump a "

Note: each word is case sensitive and if done right there should be no repetition of words.

One thing you can try is to place a space character both as prefix and suffix in each word of both strings when you convert them to lists and then remove them when you want the final output:

a = "The quick brown fox did jump over a log"
b = "The brown rabbit quickly did outjump the fox"

# Convert to list with prefix and suffix.
listA = [' ' + elem + ' ' for elem in a.split()]
listB = [' ' + elem + ' ' for elem in b.split()]

# Loop to check for each word in listA if it's in listB.
c = []
for elem in listA:
    if elem in listB:
        c.append(elem[1:-1]) # Append element without prefix and suffix.
        listB.remove(elem)

b = " ".join([elem[1:-1] for elem in listB]) # Remove prefix and suffix.
c = " ".join(c)

print("New string:", c)
print("New b:", b)

Output:

New string: The brown fox did
New b: rabbit quickly outjump the

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