"не оптимизируй раньше времени" (c) все
import re
s = "Ahjrh3892h89*@(!894y19hKJAHjjfnakjznUIZHiuhrweui"
def withsub(st):
new_s = re.sub(r'[^a-z]', '', st)
return new_s
def withfindall(st):
new_s = ''.join(re.findall('[a-z]', st))
return new_s
def withoutregex(st):
new_s = ''.join([a for a in st if a.isalpha() and a.islower()])
return new_s
ipython
In [1]: from tes import s, withsub, withfindall, withoutregex
In [2]: s
Out[2]: 'Ahjrh3892h89*@(!894y19hKJAHjjfnakjznUIZHiuhrweui'
In [3]: %timeit withsub(s)
The slowest run took 33.17 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.08 µs per loop
In [4]: %timeit withfindall(s)
The slowest run took 35.48 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.64 µs per loop
In [5]: %timeit withoutregex(s)
100000 loops, best of 3: 7.06 µs per loop