You need to check if the pattern is in each element.
To achieve this, you've to iterate (direct or indirect) over the list.
Each element in the list is a
str
.
You can check each element. The methods
startswith
and
endswith
can be used with an if-condition. Str do also support containment checking. You can look
if
a str
is
in
another str
.
courses = ['MATH201:A', 'CS222:C', 'IF100:B']
predicate = "MATH201"
for index, course in enumerate(courses):
if course.startswith(predicate):
print(course, "starts with", predicate, "at index", index)
elif predicate in course:
print(course, "is contained in", predicate, "at index", index)
# is a generator
# https://wiki.python.org/moin/Generators
def find_all(sequence, predicate):
for index, element in enumerate(sequence):
if predicate in element:
yield index
def find_first(sequence, predicate):
for first in find_all(sequence, predicate):
return first
courses = ['MATH201:A', 'CS222:C', 'IF100:B']
predicate = "MATH201"
index = find_first(courses, predicate)
if index is None:
print(predicate, "was not found.")
else:
print(predicate, "was found in sequence")
print("Index:", index)
You can use the previous defined
find_all
to get more than one result.
courses = ['MATH201:A', 'CS222:C', 'MATH201:B', 'IF100:B', 'MATH201:C']
indices = list(find_all(courses, "MATH"))
You can also use a list comprehension:
courses = ['MATH201:A', 'CS222:C', 'MATH201:B', 'IF100:B', 'MATH201:C']
indicies = [index for index, element in enumerate(courses) if "MATH" in element]
Here are the operations for sequences:
https://docs.python.org/3/library/stdtyp...operations
A str is also a sequence. All this operation could be applied on
str
.
Enumerate:
https://docs.python.org/3/library/functi...#enumerate