Home > Mobile >  Using regular expression to match and replace
Using regular expression to match and replace

Time:05-18

There is a list of string A which is some how matching with another list of string B. I wanted to replace string A with list of matching string B using regular expression. However I am not getting the correct result.

The solution should be A == ["Yogesh","Numita","Hero","Yogesh"].

import re

A = ["yogeshgovindan","TNumita","Herohonda","Yogeshkumar"]
B=["Yogesh","Numita","Hero"]

for i in A:
    for j in B:
        replaced=re.sub('i','j',i)
        
print(replaced)

CodePudding user response:

this one works to me:

lst=[]
for a in A:
    lst.append([b for b in B if b.lower() in a.lower()][0])

This returns element from list B if it is found at A list. It's necessary to compare lowercased words. The [0] is added for getting string instead of list from comprehension list.

  • Related