How to remove two chars from the beginning of a line

Viewed 82930

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
12 Answers

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).

String slicing will help you:

>>> a="Some very long string"
>>> a[2:]
'me very long string'

Just as a tip, you can shorten your program to

for line in open('M:/file.txt'):
    line = line[2:]

And if you need to carry the line number too, use

for i, line in enumerate(open('M:/file.txt.')):
    line = line[2:]

Instead of using a for loop, you might be happier with a a list comprehension:

[line[2:] for line in lines]

Just as a curiosity, do check the cut unix tool.

$ cut -c2- filename

The slicing syntax for -c is quite similar to python's.

for line in open("file"):
    print line[2:]
Related