chopping a string
Geoff Gerrietts
ggerrietts at yahoo.com
Mon Mar 4 20:01:19 EST 2002
Quoting David Bear (iddwb at moroni.pp.asu.edu):
> there's gotta be an easier way. I have a string
> " something somethingelse "
>
> note the leading a trailing whitespace. I'd like to grab the first
> word and strip whitespace. I came up with
>
> string.join(string.split(string.strip(str))[:1])
>
> but I'm thinking, there must be a better way? better means (faster) (smaller)..
That's probably what I would use, though if you're in a python that
supports string methods, you could do:
str.strip().split()[0] or "".join(str.strip().split()[:1])
The latter registers as about 1.33 times faster than (takes 3/4 as
long as) the version above; the former is 2 times faster (runs in 1/2
the time).
You could maybe do with something with re:
string.join(re.split("\s+",str)[:2])
But that won't work if you don't have leading whitespace, and it's
slower, if a bit more concise. My timings show 2500 iterations of this
at .14 seconds, while the method-based version clocks .06 and your
original at .08.
Thanks,
--G.
--
Geoff Gerrietts <ggerrietts at yahoo.com>
-rw-rw-rw-: permissions of the beast
More information about the Python-list
mailing list