ValueError: substring not found, What am I doing wrong?
item.index('1')
returns the index in your list where '1'
is found. However, '1'
is not in your example list at all. Your question states that you're "trying to select the item that begins with '1'
." Begins with "1"
and equals "1"
are not the same thing. Your requirement is itself potentially problematic, as you say "item,"
singular, but in fact three items in your list begin with "1"
.
If you want to find all the items in a list that begin with "1"
, you can use a list comprehension, like so:
[item for item in lst_Filename if item.startswith('1')]
The problem with this is that .index()
throws ValueError
when it does not find the requested item. This is why it works for the first two items, but when it reaches a string that starts with something other than 1
, it dumps an error and stops searching. To make what you want to do work you should use str.startswith()
.
Demo:
>>> lst = ['1490 2 Mo', '1267 3 Mo', '2239 6 Mo', '1449 7 Ks']
>>> [item for item in lst if item.startswith('1')]
['1490 2 Mo', '1267 3 Mo', '1449 7 Ks']
item.index('1') is raising an exception because '1' is not found in the string (https://docs.python.org/2/library/string.html#string.index). Try to use item.find('1') instead!