Splitting a string
Peter Otten
__peter__ at web.de
Fri Apr 2 17:32:58 EDT 2010
Thomas Heller wrote:
> Thanks to all for these code snippets. Peter's solution is the winner -
> most elegant and also the fastest. With an additional list comprehension
> to remove the possible empty strings at the start and at the end I get
> 16 us. Interesting is that Xavier's solution (which is similar to
> some code that I wrote myself) isn't so much slower; it get timings of
> around 22 us.
Deleting the first or last item is probably faster than looping over the
whole list. If there aren't any empty strings the overhead is constant.
_split = re.compile(r"(\d+)").split
def split(s):
if not s:
return ()
parts = _split(s)
parts[1::2] = map(int, parts[1::2])
if parts[-1] == "":
del parts[-1]
if parts[0] == "":
del parts[0]
return tuple(parts)
Peter
More information about the Python-list
mailing list