public
Last active

Speed comparison of finding if a digit exists in a string, in python.

  • Download Gist
gistfile1.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
>>> cmd = """
... for c in 'xdtwkeltjwlkejt7wthwk89lk':
... if c.isdigit():
... break;
... """
>>>
>>> timeit.Timer(cmd).timeit()
2.1454498767852783
>>>
>>>
>>> setup = """
... import re
... """
>>>
>>> cmd = """
... re.search('\d', 'xdtwkeltjwlkejt7wthwk89lk')
... """
>>>
>>> timeit.Timer(cmd, setup=setup).timeit()
1.8365380764007568
>>>
>>> cmd = """
... next((c for c in 'xdtwkeltjwlkejt7wthwk89lk' if c.isdigit()), -1)
... """
>>>
>>> timeit.Timer(cmd).timeit()
3.0304851531982422

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.