Python - Remove Last Line From String
Asked Answered
S

1

12

I'm trying to capture and manipulate data within a Telnet session using telnetlib, things are going fairly well, however my newbness with Python is causing me some headache.

My issue is pretty straight forward, I am able to capture and display the data I want (So far) however I just seem to be cycling through errors whenever I try to remove the last line of data from the data I have captured. My code goes something like this:

... Snipped Boring Stuff ...
tn.write('command to gather data' + '\r')
data = tn.read_very_eager()
print data
... snipped more boring stuff ...

Pretty simple... So, how in the world would I remove the last line of data from either tn.read_very_eager() or data() ?

Any direction would be awesome... Sorry for the really simple question, but the stuff I've read and tried so far have done nothing but frustrate me, my keyboard can't take much more abuse :)

Stoller answered 8/9, 2013 at 11:7 Comment(0)
I
24

You can remove the last line of a string like this:

def remove_last_line_from_string(s):
    return s[:s.rfind('\n')]

string = "String with\nsome\nnewlines to answer\non StackOverflow.\nThis line gets removed"

print string
string = remove_last_line_from_string(string)
print '\n\n'+string

The output will be:

>>>
String with
some
newlines to answer
on StackOverflow.
This line gets removed


String with
some
newlines to answer
on StackOverflow.
>>>
Impearl answered 8/9, 2013 at 11:25 Comment(1)
This doesn't work if there is only one line, it will delete the last character instead (whereas it should probably return the empty string). Should check if the rfind returns -1 and act accordingly.Pronunciamento

© 2022 - 2024 — McMap. All rights reserved.