Python readline() from a string?

后端 未结 5 1414
予麋鹿
予麋鹿 2020-12-23 20:21

In python, is there a built-in way to do a readline() on string? I have a large chunk of data and want to strip off just the first couple lines w/o doing split() on the who

5条回答
  •  滥情空心
    2020-12-23 20:48

    Why not just only do as many splits as you need? Since you're using all of the resulting parts (including the rest of the string), loading it into some other buffer object and then reading it back out again is probably going to be slower, not faster (plus the overhead of function calls).

    If you want the first N lines separated out, just do .split("\n", N).

    >>> foo = "ABC\nDEF\nGHI\nJKL"
    >>> foo.split("\n", 1)
    ['ABC', 'DEF\nGHI\nJKL']
    >>> foo.split("\n", 2)
    ['ABC', 'DEF', 'GHI\nJKL']
    

    So for your function:

    def handleMessage(msg):
       headerTo, headerFrom, msg = msg.split("\n", 2)
       sendMessage(headerTo,headerFrom,msg)
    

    or if you really wanted to get fancy:

    # either...
    def handleMessage(msg):
       sendMessage(*msg.split("\n", 2))
    
    # or just...
    handleMessage = lambda msg: sendMessage(*msg.split("\n", 2))
    

提交回复
热议问题