Python - Remove Last Line From String

user2735454 picture user2735454 · Sep 8, 2013 · Viewed 13.8k times · Source

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

Answer

user2746752 picture user2746752 · Sep 8, 2013

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