在python中,是否有内置的方法对字符串执行readline()?我有大量的数据,只想剥离前几行而对整个字符串不做split()。
假设的例子:
def handleMessage(msg): headerTo = msg.readline() headerFrom= msg.readline() sendMessage(headerTo,headerFrom,msg) msg = "Bob Smith\nJane Doe\nJane,\nPlease order more widgets\nThanks,\nBob\n" handleMessage(msg)
我希望这导致: sendMessage("Bob Smith", "Jane Doe", "Jane,\nPlease order...")
sendMessage("Bob Smith", "Jane Doe", "Jane,\nPlease order...")
我知道编写一个可以做到这一点的类非常容易,但是我正在寻找内置的东西。
编辑:Python v2.7
您可以使用StringIO:
>>> msg = "Bob Smith\nJane Doe\nJane,\nPlease order more widgets\nThanks,\nBob\n" >>> msg 'Bob Smith\nJane Doe\nJane,\nPlease order more widgets\nThanks,\nBob\n' >>> import StringIO >>> buf = StringIO.StringIO(msg) >>> buf.readline() 'Bob Smith\n' >>> buf.readline() 'Jane Doe\n'
如果性能很重要,请确保使用cStringIO。
您可以使用io.StringIO:
>>> import io >>> buf = io.StringIO(msg) >>> buf.readline() 'Bob Smith\n' >>> buf.readline() 'Jane Doe\n' >>> len(buf.read()) 44