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
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With