Python - 从字符串中删除最后一行

use*_*454 8 python telnetlib

我正在尝试使用telnetlib在Telnet会话中捕获和操作数据,事情进展顺利,但是我对Python的新见解让我头疼.

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 ...
Run Code Online (Sandbox Code Playgroud)

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

use*_*752 14

您可以删除字符串的最后一行,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

输出将是:

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


String with
some
newlines to answer
on StackOverflow.
>>>
Run Code Online (Sandbox Code Playgroud)

  • 如果只有一行,这将不起作用,它将删除最后一个字符(而它应该返回空字符串).应该检查rfind是否返回-1并相应地采取行动. (3认同)
  • 工作得很完美.万分感谢! (2认同)