Blog of Julian Andres Klode

March 24, 2008

Python Speed: Getting the first part of a string

Filed under: Python — Julian Andres Klode @ 23:38

If you want to get the first part of a string (in the following example a), you should use the partition method of the string, as it is the fastest way (and it also gives you the delimiter in [1] and the other part of the string in [2]):

In [1]: a = ‘a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z’

In [2]: timeit a.partition(’/')[0]
1000000 loops, best of 3: 362 ns per loop

In [3]: timeit a[:a.find('/')]
1000000 loops, best of 3: 443 ns per loop

In [4]: timeit a.split(’/', 1)[0]
1000000 loops, best of 3: 697 ns per loop

In [5]: timeit a.split(’/')[0]
1000000 loops, best of 3: 1.45 µs per loop

These tests were made with IPython 0.8.1 (Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) ) on an Ubuntu 64 bit system.

2 Comments »

  1. By the way, I think sequence unpacking is slightly faster than indexing:

    x, _, _ = a.partition(’/')

    Comment by Alexandre — March 26, 2008 @ 05:57

  2. If the string in “a” is a bit different, resultat is different too O :)

    In [1]: a = ‘ijtgvtrVC/ytrvyvcytv/vcytvcyt’

    In [2]: timeit a.split(’/', 1)[0]
    1000000 loops, best of 3: 847 ns per loop

    In [3]: timeit a.split(’/')[0]
    1000000 loops, best of 3: 850 ns per loop

    Comment by elghinn — May 2, 2008 @ 12:17

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.