Skip to content Skip to sidebar Skip to footer

Don't Understand Why String.index("word") Isn't Working

Is it possible that the method .index('word') in python does not work? I have this list: ['Viganello\n', 'Monday\n', '06 | 48\n', '06 | 58\n', '07 | 08\n', '07 | 18\n', '07 | 28\n

Solution 1:

Your very first line doesn't have that character:

'Viganello\n'

Neither does the second:

'Monday\n'

Only from the third line onwards is that character present:

'06 | 48\n'

I suspect you want to perhaps split your lines on that character; don't use str.index(); you can use str.split() instead; it has the added advantage that that will work even if the character is not present in a line. Use:

parts = [part.strip() for part in line.split('|')]

and you'll get a list of elements from your input line, split on the | character, guaranteed. That list might contain just one element, but that shouldn't matter.

If you really must have the index of the | character, you can use str.find() and test for -1 to see if it was missing, or use try..except to catch the IndexError:

a = line.find('|')
if a == -1:
    # oops, no such character

or

try:
    a = line.index('|')
except IndexError:
    # oops, no such character

Solution 2:

Some of your strings don't have | in them, hence the exception. I'd suggest using line.find() in place of line.index(), and checking the return value for -1.

Solution 3:

Your first line: "Viganello\n" does not have the "|", and raises the ValueError you're getting.

Either check for it before getting the index:

for line in lines:
    if "|" in line:
        print(line.index("|"))

Or use a try statement to catch the ValueError

Or even easier, use str.find() instead of str.index(), which does not raise the ValueError:

for line inlines:
    print(line.find("|"))

Post a Comment for "Don't Understand Why String.index("word") Isn't Working"