Try to find an element in the list based on a part of the string

I have a list = ['Assassin Bow', 'Bone Bow', 'Citadel Bow'] and I have a string = 'Bone Bow of Fire'

How can I get output 'Bone Bow' as the result ? Just started codding, thx for understanding.

Upvotes: 0

Views: 134

Answers (2)

Yilun Zhang
Yilun Zhang

Reputation: 9018

You can check iteratively to see if an element in list is included in string or not.

The very basic is to use a for loop:

result = []
for item in list:
    if item in string:
        result.append(item)

A more comprehensive way:

result = [i for i in l if i in s]

This will return a list containing all elements that satisfies the condition. In your example, it will be a list of one item, but for other cases, there can be more.

Notes:

  • list is a predefined function/class in python, so do NOT name your variables with it.
  • string is technically allowed, but it's a better practice not to use it. You should name your variables cleverer and more meaningful.

Upvotes: 2

ObjectJosh
ObjectJosh

Reputation: 641

l = ['Assassin Bow', 'Bone Bow', 'Citadel Bow']
s = 'Bone Bow of Fire'

# loop through each element in list 'l'
for x in l:
    # if the element is somewhere in the string 's'
    if x in s:
        print(x)

Upvotes: 2

Related Questions