4 回答

TA貢獻2011條經驗 獲得超2個贊
你可以使用正則表達式做這樣的事情:
import re
txts = ["34291.daveabc2712144.txt",
"eidddvabc24156.mp3",
"beonabcsimple.csv",
"fABCgfdge.txt"]
for i in txts:
x = re.findall("abc.{5}", i)
#if you need to be case insensitive you can do this
#x = re.findall("abc.{5}", i, re.IGNORECASE)
if x:
print(x)

TA貢獻1777條經驗 獲得超3個贊
以下是如何使用該glob模塊。假設所有的abc都是小寫的:
from glob import glob
for file in glob('*abc*'): # For every file that has 'abc' in it
i = file.find('abc') # Find the index of the 'abc'
print(file[i:i+8]) # Print out the file name 5 characters from the end of 'abc', or 8 from the start
這樣做的好處是:glob('*abc*')這樣我們就不會首先列出所有'abc'文件,只列出名稱中包含的文件。

TA貢獻1797條經驗 獲得超6個贊
>>> s = '34291.daveabc2712144.txt'
>>> s[(start := s.index('abc')): start + 8]
'abc27121'
假設海象運算符'abc'可以找到并且需要 Python 3.8+。
在我看來,這樣一個簡單的任務不需要正則表達式。

TA貢獻1796條經驗 獲得超10個贊
您可以使用正則表達式:
abc.{5}
在Python:
import re
strings = ["34291.daveabc2712144.txt", "eidddvabc24156.mp3", "beonabcsimple.csv"]
rx = re.compile(r'abc.{5}')
names = [m.group(0) for string in strings for m in [rx.search(string)] if m]
print(names)
添加回答
舉報