How can I remove the first line of a multi-line string?

Terry Reedy tjreedy at udel.edu
Mon Sep 2 18:19:17 EDT 2013


On 9/2/2013 12:06 PM, Anthony Papillion wrote:

> I have a multi-line string and I need to remove the very first line from
> it. How can I do that? I looked at StringIO but I can't seem to figure
> out how to properly use it to remove the first line. Basically, I want
> to toss the first line but keep everything else.  Can anyone put me on
> the right path? I know it is probably easy but I'm still learning Python
> and don't have all the string functions down yet.

Simply splitting off the first line, using the maxsplit parameter, is 
more efficient that splitting all lines and joining all but the first. I 
presume you also want to remove a single line without \n to split on.

def keeprest(s):
     try:
         return s.split('\n', 1)[1]
     except IndexError:
         return ''

for s in ('', 'a', 'a\n', 'a\nrest\n'):
         print('for', repr(s), 'kept:', repr(keeprest(s)))
 >>>
for '' kept: ''
for 'a' kept: ''
for 'a\n' kept: ''
for 'a\nrest\n' kept: 'rest\n'

MRAB's s.partition('\n')[2] has exactly the same result as keeprest(s) 
as, by design, it handles the no-separator case and always returns a 
triple. I believe it is the equivalent (in C for CPython) of

def partition(self, string, splitter):
   try:
     first, rest = string.split(splitter, maxsplit=1)
     return (first, splitter, rest)
   except ValueError:  # from impossible assignment of 1 item to 2 names
     return (string, '', '')

---

If you have *any* iterable of lines and want to process the first line 
differently than the rest (including just ignoring it), you can use

first = True:
for line in lines:
   if first:
     process_first(line)
     first = False
   else:
     process_rest(line)

*or*

it = iter(sometext)
try:
   first = next(it)
except StopIteration:  # always catch this with explicit next
   pass

At this point, *it* now represents the rest of the text and you can pass 
it to any function expecting an iterable of lines.

-- 
Terry Jan Reedy




More information about the Python-list mailing list