[Tutor] line iteration in a file
Cameron Simpson
cs at zip.com.au
Thu Jun 4 05:09:33 CEST 2015
On 03Jun2015 22:37, richard kappler <richkappler at gmail.com> wrote:
>Figured out the string delimiters problem, thanks for all the help. Now
>I've run into another.
>
>I've used the re.finditer that I think it was Peter suggested. So I have:
>
>for line in file:
> s = line
> t = [m.start() for m in re.finditer(r"]", s)]
> q = len(t)
>
>which works fine, in testing it finds the number and position of the ]'s in
>any line I throw at it. I then wrote a series of if/elif statements based
>on q, in other words
>
>if q == 1:
> do something
>elif q == 2:
> do something else
>elif q == 3:
> do a third thing
>else:
> pass
>
>as I looked through enough example to figure out that the most ]'s I can
>have is 3, but the pass is there just in case.
>
>I keep getting a list index out of range error, and my best guess is that
>it's because t and q are set on the first line read, not each line read, is
>that right? If not, what might be the problem and either way, how do I fix
>it?
Please post a self contained example (i.e. small complete code, not snippets)
and a transcribe of the full error message with stack backtrace. What you have
above is not enough to figure out what is going wrong. If what you display
above is accurate then t and q are set for every line read.
Another remark, what is the use of your "else: pass" code? Normally one would
put some action here, such as raising an exception for the unhandled value or
issuing a warning.
Cheers,
Cameron Simpson <cs at zip.com.au>
My computer always does exactly what I tell it to do but sometimes I have
trouble finding out what it was that I told it to do.
- Dick Wexelblat <rlw at ida.org>
More information about the Tutor
mailing list