-   Programming (
-   -   How to remove lines and parts of lines from python strings? (

golmschenk 11-24-2009 10:43 PM

How to remove lines and parts of lines from python strings?
How do you remove parts of strings using python? Such as, if I have something like:

erme1 sdifskenklsd
erme2 sdfjksliel
erme3 kcielsmkdlfdsiof
erme4 mvieksldiskld
erme5 cidfksldosldk

How could I have python remove the erme# in front of each row? Is there a way to do it by removing the erme plus what ever is attached to it? Or just remove the first 5 characters of each row? Or is there an option for each? I'd like to know how to do both, but I'd be happy with just one.

Another case, how would I have python remove something like:

4:32 aips mana seven
4:32 aips mana seven
4:33 aips mana seven
4:33 aips mana seven
4:34 aips mana seven

How could I remove the entire line starting with the time leaving the rest, when the same time could be repeated any number of times before moving to the next time?

Thanks for your time!

nc3b 11-24-2009 11:39 PM

Hello !

You (probably) need to use regular expressions:

Just to get you started:


>>> re.sub('^erme[0-9]*\s', '', 'erme3 kcielsmkdlfdsiof')

Of course I do have to warn you I don't python every day so there may be better ways of doing this.

Cheers :)

ghostdog74 11-25-2009 01:46 AM

@OP, you probably should read up the docs for a start.

for you first question and with your sample data, you can just do a split(), then remove the first column

for line in open("file"):
    print ' '.join(line.split()[1:])

to remove first 5 characters

print line[4:]
these are just the basics. so read up the docs, then try to do the third problem. Regex expression?? NO NEED.

golmschenk 11-26-2009 11:29 PM

Great thanks. I think I will read more documentation.

All times are GMT -5. The time now is 05:52 AM.