def get_file():
lst_Filename = []
while True:
Filename = input('\nPlease enter name of ballot file: ')
try:
read_Filename = open(Filename, 'r')
txt_Filename = read_Filename.readlines()
lst_Filename = [word.strip() for word in txt_Filename]
read_Filename.close()
return lst_Filename
except IOError:
print("The file",Filename,"does not exist.")
continue
lst_Filename = get_file()
lst2 = {}
for item in lst_Filename:
if item.index('1') == 0:
print(item)
The lst_Filename is structured as follows: ['1490 2 Mo', '1267 3 Mo', '2239 6 Mo', '1449 7 Ks'], the actual file contains hundreds of items in the list.
I am trying to select the item that begins with '1'. When I run the program, the first two items is printed
1490 2 Mo
1267 3 Mo
then I get the ValueError: substring not found, it says the problem is with the line "if item.index('1') == 0:", i assume because '2239 6 Mo' does not begin with '1'
What I don't understand is that my codes says for every item in the lst_Filename, if that item(which is a string) has the substring '1' in its 0 index then select the item.
Isn't the 'if' a selection statement, why doesn't the program skips through items that don't begin with '1'.
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!
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')
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With