How can I remove the first line of a multi-line string? (SOLVED)
Roy Smith
roy at panix.com
Wed Sep 11 09:03:27 EDT 2013
In article <mailman.244.1378901307.5461.python-list at python.org>,
Fábio Santos <fabiosantosart at gmail.com> wrote:
One suggested solution:
> > > > sansfirstline = '\n'.join(fullstring.split('\n')[1:])
To which I suggested a couple of alternatives:
> > i = s.index('\n')
> > print s[i+1:]
> > [...]
> > print re.sub(r'^[^\n]*\n', '', s)
> > I'll admit, the split/slice/join solution is probably the easiest to
> > implement (and to understand when you're reading the code). But, it
> > copies all the data twice; once when split() runs, and again when join()
> > runs. Both the index and regex solutions should only do a single copy.
> > For huge strings, this might matter. For a three-liner as in your
> > example, it doesn't make any difference.
> >
>
> Is there not a limit argument to str.split? This should be trivial.
>
> first, rest = multiline_str.split('\n', 1)
This certainly prevents the extra splitting and re-compositing of the
additional lines.
One thing to watch out for is that split(s, 1) does *at most* 1 split.
If the original string didn't have any newlines, you would end up with a
single-item list and the unpack would fail. You can get around that
with:
rest = multiline_str.split('\n', 1)[-1]
but that's kind of cryptic.
Looking back at my solutions suggested above, s.index() fails in the
same situation (throws ValueError). The regex solution works fine, once
again proving that 1970's technology is still superior to all this
newfangled stuff.
A coworker recently introduced me to what is apparently a classic essay
(http://www.team.net/mjb/hawg.html). If Unix is the Hole Hawg of
operating systems, then regexes are the Hole Hawg of string processing
tools. Those of us who grew up around them, appreciate their power and
have learned how to use them without chopping off any fingers. And we
look on with a mix of amusement and pity at the current crop of
programmers who play with index(), split(), startswith(), rpartition(),
etc and think they're using real tools :-)
For the record, I have never used a Hole Hawg. I do, however, own a
Milwaukee 1/2" drill. Which also comes with the screw-in handle for
two-handed operation. I've had that get away from me a couple of times,
so I figure it's about my limit. Torque is a wonderful thing until the
thing you're drilling into weighs more than you do.
More information about the Python-list
mailing list