Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Remove Last Line From String

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

like image 475
user2735454 Avatar asked Sep 08 '13 11:09

user2735454


1 Answers

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.
>>>
like image 60
user2746752 Avatar answered Oct 15 '22 15:10

user2746752