0

For example

string1 = "Hello this is the first string, it will be used in this project"

string2 = "Hello this is string2 and i will not be used in this project"

i want this script to return all matching expressions in string1 from string2

output should be : [Hello this is, will, be used in this project]

i've made a custom function to achieve this using a loop but i'm afraid it's too slow

Here is my custom function, i'm sure it's terrible in so many ways but i'm still learning python.

from re import search
fullstring = "Hello this is the first string, it will be used in this project"
substring = "Hello this is string2 and i will not be used in this project"
last_found_str = ""
#while string is not empty keep looping
while test_substring:
    print("Searching for {}".format(test_substring))

    #if substring in fullstring
    if search(r'\b{}\b'.format(test_substring), fullstring):
        print("Found! : {}".format(test_substring))
        #add to list
        phrases_list.append(test_substring)
        #remove the found substring
        substring = substring.replace(test_substring,'')
        if substring == " ":
            break
        test_substring = substring
        #this is the substring from the last found results
        last_found_str = substring
    else:
        #if only one word is left
        if len(test_substring.split()) == 1:
            print("{} is not found".format(test_substring))
            if len(last_found_str.split()) > 1:
                #if substring from last found results is more than 1 word, remove the first word and loop through the rest
                substring = substring.replace(r'\b{}\b'.format(test_substring),'')
                test_substring = last_found_str.partition(' ')[2]
                last_found_str = test_substring
            else:
                #if its a word or less then stop looping
                break
        else:
            #if there is more than one word remove the last word and keep looping
            test_substring = test_substring.rsplit(' ', 1)[0] 

print(phrases_list)
lamfee
  • 11
  • 4

2 Answers2

0

Here's a list comprehension that should do the job :

[i for i in string1.split() if i in string2.split()]

Output:

['Hello', 'this', 'is', 'will', 'be', 'used', 'in', 'this', 'project']
ImranD
  • 320
  • 1
  • 6
-2

I dont know exactly how is your output, but i thing is this.

str1="Hello this is the first string, it will be used in this project"
str2 = "Hello this is string2 and i will not be used in this project"
str3=str1.split()
str4=str2.split()
str5=""
for i in range(0,len(str3)):
  if(str3[i]==str4[i]):   
    str5+=str3[i]
    str5+=" "
print(str5)

Output is a string:

Hello this is be used in this project 
dani
  • 34
  • 4