Skip to content Skip to sidebar Skip to footer

Python: Find Substring In List Of String

I have two lists: songs is a list of song titles, filenames is a list of song MP3 files that is generated by running os.listdir(). songs = ['The Prediction', 'Life We Chose', 'Nast

Solution 1:

Here is a version that will maintain the file extension, whatever it was, and will avoid that the same filename is matched twice by deleting it from the filenames array after a match. It also is case insensitive:

for song in songs:
    for i, filename in enumerate(filenames):
        if song.upper() in filename.upper():
            os.rename(filename, song + os.path.splitext(filename)[1])
            del filenames[i]
            break

You could also loop first over the file names, but then the problem can also be that two file names match with the same song, and the rename operation will raise an error on the second. So in that set up you'd better delete the song from the songs list once it has been matched with a file name.

Solution 2:

After having defined the lists as you did, you want to iterate through each file and then check it against every song name. It should look something like this:

for f in filenames:
    for s in songs:
        if s in f:
            os.rename(f,s+".mp3")

This way, the file stays with an mp3 extension as well.

Post a Comment for "Python: Find Substring In List Of String"