python split() vs rsplit() performance?

Below is a time test using timeit.timeit to compare the speeds of the two methods:

>>> from timeit import timeit
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".split(",", 1)')
1.6438178595324267
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".rsplit(",", 1)')
1.6466740884665505
>>>

As you can see, they are about equivalent. str.split is a few fractions of a second faster, but that is really unimportant. So, you can pick whichever method you want.

P.S. Although, the str.split method is one less character to type. :)


I'm super late to this party, but for anyone else stumbling across this, partition is faster than split(x, 1):

>>> from timeit import timeit
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".split(",", 1)')
0.23717808723449707
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".rsplit(",", 1)')
0.20203804969787598
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".partition(",")')
0.11137795448303223
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".rpartition(",")')
0.10027790069580078

And you can ditch the , easily if you want by h, _, t = s.rpartition(',') or such.


I think there is a slight difference between split() and rsplit(): for example:

str1 = "w,e,l,c,o,m,e"
print(str1.split(',',2))

str1 = "w,e,l,c,o,m,e"
print(str1.rsplit(',',2))

You see, split() is used if you want to split strings on first occurrences and rsplit() is used if you want to split strings on last occurrences.