I have a problem of false negative during a loop in python.
That's my list:
l = ['modello', 'modello1', 'modello_old', 'new_modello']
and that's a string:
db = '/home/user/modello1.sqlite'
What I want to do is to filter the db
string and to output the element of the list that appear in the string.
So the result should be only modello1
.
This is my loop:
for i in l:
if i in db:
print i
but the result is not what I would like to obtain:
modello
modello1
how can I match the exact word?
EDIT : the problem could be that db
is OS dependent so /
could be transformed in \\
.
EDIT2 : with @Karoly-Horvath solution:
transform the db in a list:
db = [os.path.basename(db).replace('.sqlite', '')]
loop the element of db
in the whole list:
for i in db:
if i in l:
print i
Use a regular expression or string functions to extract the relevant part:
m = os.path.basename(db).replace('.sqlite', '') # 'modello1'
or (this was the original answer, only works for unix paths)
m = db.split('/')[-1].replace('.sqlite', '') # 'modello1'
Now you can check for an exact match:
m in l # True
If you want to check against the filename without the extension, use os.path.basename
and os.path.splitext
:
>>> from os import path
>>> s = '/home/user/modello1.sqlite'
>>> path.basename(s)
>>> 'modello1.sqlite'
>>> path.splitext(path.basename(s))
('modello1', '.sqlite')
>>> filename = path.splitext(path.basename(s))[0]
>>> filename
'modello1'
Using the filename:
>>> possibles = ['modello', 'modello1', 'modello_old', 'new_modello']
>>> for possible in possibles:
... if possible in filename:
... print possible, 'in', filename
modello in modello1
modello1 in modello1
If you just want to check whether any of the possibilities match:
>>> if any(possible in filename for possible in possibles):
... print filename
modello1
I think I understand now that OP would want an exact match:
>>> if filename in possibles:
... print filename
modello1
This won't match modello
.
import os
db_basename = os.path.basename(db)
db_basename = os.path.splitext(db_basename)[0] # remove extension
use os
to get file name
How about this
for i in l:
if '/'+i+'.' in db:
print i
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.