Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove two chars from the beginning of a line

Tags:

python

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 
like image 676
rjuuser Avatar asked Aug 13 '09 09:08

rjuuser


People also ask

How do I remove the first two characters of a string?

To remove the first 2 characters from a string, use the slice method, passing it 2 as a parameter, e.g. str. slice(2) . The slice method returns a new string containing the specified portion of the original string.


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

like image 119
Amber Avatar answered Sep 24 '22 04:09

Amber