Skip to content

Instantly share code, notes, and snippets.

@moskytw
Created April 17, 2013 17:48
Show Gist options
  • Save moskytw/5406312 to your computer and use it in GitHub Desktop.
Save moskytw/5406312 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
def simple_replace(s):
return s.replace('A', 'a').replace('B', 'b').replace('C', 'c')
def dynamic_replace(s):
for t in 'ABC':
s = s.replace(t, t.lower())
return s
upper_re = re.compile('[ABC]')
def re_replace(s):
global upper_re
return upper_re.sub(lambda m: m.group().lower(), s)
if __name__ == '__main__':
s = 'aAabBbcCc'
print simple_replace(s)
print dynamic_replace(s)
print re_replace(s)
from timeit import timeit
print timeit(lambda: simple_replace(s))
# -> 1.07289290428
print timeit(lambda: dynamic_replace(s))
# -> 1.91307997704
print timeit(lambda: re_replace(s))
# -> 4.73019194603
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment