Search code examples
pythonlistclassassert

Check if any list items are in a string


I have created a class that checks if any item of the list self._name is in the string song1. I use assert to check if it is True. If I change assert with print, I get that the result is None, which is why I the assert does not work. It should come out as True, but I am unsure what I am doing wrong.

class Song:
    def __init__(self, artist, title):
        self._artist = artist
        self._title = title
            
    def checkArtist(self, name):
        self._name = name.split() #split to list since just a first name or last name is allowed
        any(artistname in self._artist for artistname in self._name)

def main_program():
    song1 = Song("Lady Gaga and Bradley Cooper", "Shallow")

    #test, should return True for both asserts since the first is an exact match and the second contains "Gaga"
    assert(song1.checkArtist("Lady Gaga and Bradley Cooper"))
    assert(song1.checkArtist("Lord Gaga"))
main_program() 

It works when I isolate it outside the class. I am not too familiar with using classes, so I might have done something wrong with the class.

song2="Lady Gaga and Bradley Cooper"

name2="Lord Gaga"
name2=name2.split()

any(namecheck in song2 for namecheck in name2) #returns True

Solution

  • class Song:
        def __init__(self, artist, title):
            self._artist = artist
            self._title = title
                
        def checkArtist(self, name):
            return any(artistname in self._artist for artistname in name.split())
    

    You need to return your boolean value!