Home > Software design >  How can I write a python code that searches for a word in a string and then prints the string if wor
How can I write a python code that searches for a word in a string and then prints the string if wor

Time:06-23

Here is a scenario:

Given:

facility_list = ['port', 'airport']

location_list =[ 'new york', 'Manchester', 'lagos port','florida port', 'london','Durban airport' ]

Task:

For each location in location_list,

If its name has 'port' or 'airport' in it,

print: {name} is cool! .

CodePudding user response:

Try:

facility_list = ["port", "airport"]
location_list = [
    "new york",
    "Manchester",
    "lagos port",
    "florida port",
    "london",
    "Durban airport",
]

for name in location_list:
    if any(facility in name for facility in facility_list):
        print(f"{name} is cool!")

Prints:

lagos port is cool!
florida port is cool!
Durban airport is cool!

OR: If you want to check separate words in location name, you can use str.split():

for name in location_list:
    if any(facility in name.split() for facility in facility_list):
        print(f"{name} is cool!")
  • Related