rjuuser rjuuser - 5 months ago 7
Python Question

How to remove two chars from the beginning of a line

I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:

#!/Python26/

import re

f = open('M:/file.txt')
lines=f.readlines()

i=0;
for line in lines:
line = line.strip()
#do something here

Answer

You were off to a good start. Try this in your loop:

for line in lines:
    line = line[2:]
    # do something here

The [2:] is called "slice" syntax, it essentially says "give me the part of this sequence which begins at index 2 and continues to the end (since no end point was specified after the colon).