tiberhockey
tiberhockey

Reputation: 576

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

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")

Upvotes: 0

Views: 102

Answers (4)

JF Amuka
JF Amuka

Reputation: 11

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()

Upvotes: 1

Kunal Sharma
Kunal Sharma

Reputation: 426

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()

Upvotes: 1

mad_
mad_

Reputation: 8273

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()

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191701

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)

Upvotes: 2

Related Questions