簡體   English   中英

Python:檢查字符串是否與列表中的 substring 匹配,返回 substring 的索引

[英]Python : Check if string matches a substring in a list, return index of a substring

我需要檢測字符串是否與列表中包含的 substring 匹配,並獲取匹配的 substring 的索引以將值分配給變量。 這是代碼:

filename = "rec_1.2_LUNCHPLAY_20220616_1645.mp4"
year = '2022'

studio = ['arena', '-1.2', '1.2', '1.3', '1.4', '1.5', '1.8', '1.9', '2bis']
month = [f'{year}01', f'{year}02', f'{year}03', f'{year}04', f'{year}05', f'{year}06']

我期待 output 是[2][5]

有人可以幫助我嗎?

使用enumerate()遍歷列表中的項目並跟蹤當前項目的 position。

for position, substring in enumerate(substrings):
    if substring in message:
        print(position)
        break

但是,即使您不了解enumerate ,還有另一個使用range()的簡單解決方案:

for position in range(len(substrings)):
    if substrings[position] in message:
        print(position)
        break
filename = "rec_1.2_LUNCHPLAY_20220616_1645.mp4"
year = '2022'

studio = ['arena', '_1.2', '1.2', '1.3', '1.4', '1.5', '1.8', '1.9', '2bis']
month = [f'{year}01', f'{year}02', f'{year}03', f'{year}04', f'{year}05', f'{year}06']

studio_index = None
month_index = None

for idx, st_match in enumerate(studio):
    if st_match in filename:
        studio_index = idx
        break

for idx, mo_match in enumerate(month):
    if mo_match in filename:
        month_index = idx
        break

print(f'studio index: {studio_index}')
print(f'month index: {month_index}')

結果:

studio index: 2
month index: 5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM