Why 'string index out of range' comes up in this code?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Why 'string index out of range' comes up in this code?

Ichiro
Hi,

I am trying to make an assembler for symbol free programs by Python. I used the strip function to remove blanks before the initial letter of each line in the Assemble file. However the error 'string index out of range' occurred and I could not figure out why.

I wrote a code as shown below just to figure out the error reason. You can see a sample file 'ex0.txt' below as well.

--------------------------------------------
f1=open('ex0.txt','r')
f2=open('ex1.txt','w')
for i in f1:
    f2.write(i.strip()[0]+'\n')
f1.close()
f2.close()


--------------------------------------------
(ex0.txt)
//long time no see

//Hi

Name
        Ichiro
--------------------------------------------
I really appreciate it if you could help me figure out.
Reply | Threaded
Open this post in threaded view
|

Re: Why 'string index out of range' comes up in this code?

WBahn
Administrator
The most likely cause is that your last line in the input file is a blank line with no characters it is.
Reply | Threaded
Open this post in threaded view
|

Re: Why 'string index out of range' comes up in this code?

Ichiro
Thank you very much for your reply. I could execute it when I got rid of the blank line.
Now I figured out how to skip blank lines, I can delete blank lines and comment lines in the project.