Python: how to find the presence of each list item in a string

What is the most pythonic way to find the presence of each directory name ['spam', 'eggs']in a path, for example."/home/user/spam/eggs"

Usage example (does not work, but explains my case):

dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
if path.find(dirs):
    print "All dirs are present in the path"

thanks

+3
source share
5 answers

set.issubset:

>>> set(['spam', 'eggs']).issubset('/home/user/spam/eggs'.split('/'))
True
+9
source

Selects the line you want something like ...:

if all(d in path.split('/') for d in dirs):
   ...

This one-line style is inefficient, as it maintains a splitting path for each d (and split makes a list, while a set is better for membership verification). Introducing it in 2-layer:

pathpieces = set(path.split('/'))
if all(d in pathpieces for d in dirs):
   ...

significantly improves performance.

+5
source
names = ['spam', 'eggs']
dir   = "/home/user/spam/eggs"

# Split into parts
parts = [ for part in dir.split('/') if part != '' ]

# Rejoin found paths
dirs  = [ '/'.join(parts[0:n]) for (n, name) in enumerate(parts) if name in names ]

: , :

parts = "/home/user/spam/eggs".split('/')

print all(dir in parts for dir in ['spam', 'eggs'])
+2

, , ?

dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
present = [dir for dir in dirs if dir in path]
+1

One insert using generators (using text search and not treating names like anything related to the file system - your request is not entirely clear to me)

[x for x in dirs if x in  path.split( os.sep )]
0
source

Source: https://habr.com/ru/post/1718124/


All Articles