Pricylla
Pricylla

Reputation: 43

Check if text contains a string and keep matched words from original text:

a = "Beauty Store is all you need!"
b = "beautystore"
test1 = ''.join(e for e in a if e.isalnum())
test2 = test1.lower() 
test3 = [test2]
match = [s for s in test3 if b in s]
if match != []:
    print(match)
>>>['beautystoreisallyouneed']

What I want is: "Beauty Store"

I search for the keyword in the string and I want to return the keyword from the string in the original format (with capital letter and space between, whatever) of the string, but only the part that contains the keyword.

Upvotes: 0

Views: 41

Answers (1)

user8408080
user8408080

Reputation: 2468

If the keyword only occurs once, this will give you the right solution:

a = "Beauty Store is all you need!"
b = "beautystore"

ind = range(len(a))

joined = [(letter, number) for letter, number in zip(a, ind) if letter.isalnum()]

searchtext = ''.join(el[0].lower() for el in joined)

pos = searchtext.find(b)

original_text = a[joined[pos][1]:joined[pos+len(b)][1]]

It saves the original position of each letter, joins them to the lowercase string, finds the position and then looks up the original positions again.

Upvotes: 1

Related Questions