Search code examples
pythonstringsetextractunions

Extracting string from another string in python


I have two lists

a = ['Shri Vatsav Ltd','Paytm Pvt ltd','Paypal ltd']
b = ['Shri Vatsav Ltd 123 HAL 2nd Stage Indiranagar Banagalore 560008','Paytm Pvt ltd 143 Jallianwallabagh Mumbai India 34567','Paypal ltd 345 Greenwood drive 123ST Long Beach CA 34566 US']

I need to extract only the address from list "b" using list "a" i.e, some kind of intersection or something like that. and store it as a list called "c"

Please find the example output:

output

['123 HAL 2nd Stage Indiranagar Banagalore 560008','143 Jallianwallabagh Mumbai India 3456','345 Greenwood drive 123ST Long Beach CA 34566 US']

Thank you.


Solution

  • a = ['Shri Vatsav Ltd', 'Paytm Pvt ltd', 'Paypal ltd']
    b = ['Shri Vatsav Ltd 123 HAL 2nd Stage Indiranagar Banagalore 560008','Paytm Pvt ltd 143 Jallianwallabagh Mumbai India 34567','Paypal ltd 345 Greenwood drive 123ST Long Beach CA 34566 US']
    
    c = [i.replace(j, "") for i in b for j in a if j in i]
    print(c)  # [' 123 HAL 2nd Stage Indiranagar Banagalore 560008', ' 143 Jallianwallabagh Mumbai India 34567', ' 345 Greenwood drive 123ST Long Beach CA 34566 US']