如何在re.findall中使用变量?



我对Python非常陌生,所以如果我的问题相当愚蠢,我很抱歉。我在一个列表中有一些长字符串而在另一个列表中有一些缩短的字符串

:

长字符串为D:\Python\Songs\testsong.mp3,短字符串为\testsong.mp3

我想得到一个包含"歌曲"的列表(基本上是包含mp3的文件夹的名称),但我有多个文件夹和多首歌曲,所以我试图使用re.findall,但它只接受定义的模式,我的模式因不同的歌曲名称而改变。

from pathlib import Path
directories = [
    "D:/Python/Songs/testsong.mp3",
    "C:/users/xyz/desktop/anothersong.mp3"
]
song_folder_names = set(Path(directory).parts[-2] for directory in directories)
print(song_folder_names)

输出:

{'desktop', 'Songs'}
>>> 

请注意,文件夹名称的顺序没有保留-因为我使用的是set .

最新更新