Home > Net >  How to print the character that has been found on my string?
How to print the character that has been found on my string?

Time:10-30

I have a string where I want to search if some words are in it. (Multiple words)

How can I print the word that got found in the string?

Here is my code:

MLB_team = {
   'Colorado' : 'Rockies',
   'Boston'   : 'Red Sox',
    'Minnesota': 'Twins',
    'Milwaukee': 'France',
   'Seattle'  : 'Mariners'
 }


def location():
    mlb_str = str(MLB_team)
    location = ["Cuba", "France", "USA"]

    if any(x in mlb_str for x in location):
        print("yes")

    else:
        print("no")

location()

For now it print "yes" because the word "France" is on the Mlb _team string. But I would also like to print the word that has been found in the string ("France")

CodePudding user response:

You'd want to use a loop to get access to the exact element that is found.

for x in location:
    if x in str(MLB_team):
        print(x)
        continue  # if you only want the first

However, rather than using a string of the entire dictionary, I suggest looping over its keys and values individually

for k, v in MLB_team.items():
    for x in location:
        if x in str(k):
            print(k, x)
        if x in str(v):
            print(v, x)

CodePudding user response:

you can do it like this:

MLB_team = {
   'Colorado' : 'Rockies',
   'Boston'   : 'Red Sox',
    'Minnesota': 'Twins',
    'Milwaukee': 'France',
   'Seattle'  : 'Mariners'
 }


def location():
    mlb_str = str(MLB_team)
    location = ["Cuba", "France", "USA"]
    flag = False

    for x in location:
        if x in mlb_str:
            print(x)
            flag = True

    if flag:
        print("yes")
    else:
        print("no")

location()

CodePudding user response:

def location():
    location = ["Cuba", "France", "USA"]
    #1. get the dict keys and store in list
    mlbkey_list = []
    for x in MLB_team.keys():
        mlbkey_list.append(x)
    #2. repeat same for values
    mlbvalues_list = []
    for x in MLB_team.values():
        mlbvalues_list.append(x)
    #3. merge both lists
    mainlist = mlbkey_list   mlbvalues_list
    #4. compare 2 lists
    for x in location:
        for y in mainlist:
            if x == y:
                print(f"Yes: {x}")
            else:
                print("No")
location()

CodePudding user response:

You can have a set intersection like this

def location():
    location = ["Cuba", "France", "USA"]

    my_set = {*MLB_team.keys(), *MLB_team.values()}
    print(my_set.intersection(set(location)))

location()
  • Related