LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   How to remove lines and parts of lines from python strings? (http://www.linuxquestions.org/questions/programming-9/how-to-remove-lines-and-parts-of-lines-from-python-strings-771366/)

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:
Code:

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:
Code:

4:32 aips mana seven
dfkjdsfjlfdsjkfdskjlfdskjldsf
fdsnhjfdsnfgewonkclewnloew
fdsjewofenwjlkfewniofewnkilew
dsnkjlfewniofewnjkldsienklew
4:32 aips mana seven
fdsjklfdsjfeiodfsnkvdslkdsl
sfdnklfdsknlfdsnlkfdlkds
fdsnklfdslkfdslkfdslkfdslkdfs
fdsnklfdsklndsnlkfdsnkldsnkdl
4:33 aips mana seven
fdsjkdsfkljdsfkjdsopejwkl
wejiofejlfdemskfdsjmkflds
4:33 aips mana seven
fdsjfdsfdslkfjkldsfjkfdsjk
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:

http://docs.python.org/library/re.html

Just to get you started:

Code:

>>> re.sub('^erme[0-9]*\s', '', 'erme3 kcielsmkdlfdsiof')
'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
Code:

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

to remove first 5 characters
Code:

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 08:36 PM.