The timing of various implementations is just for fun:
#!/usr/bin/env python import random def f1(s): return ''.join(random.choice([x.upper(), x]) for x in s) def f2(s): return ''.join((x.upper(), x)[random.randint(0, 1)] for x in s) def f3(s): def randupper(c): return random.random() > 0.5 and c.upper() or c return ''.join(map(randupper, s)) def f4(s): return ''.join(random.random() > 0.5 and x.upper() or x for x in s) if __name__ == '__main__': import timeit timethis = ['f1', 'f2', 'f3', 'f4'] s = 'habia una vez... truz' for f in timethis: print '%s: %s' % (f, timeit.repeat('%s(s)' % f, 'from __main__ import %s, s' % f, repeat=5, number=1000))
These are my times:
f1: [0.12144303321838379, 0.13189697265625, 0.13808107376098633, 0.11335396766662598, 0.11961007118225098] f2: [0.22459602355957031, 0.23735499382019043, 0.19971895217895508, 0.2097780704498291, 0.22068285942077637] f3: [0.044358015060424805, 0.051508903503417969, 0.045358896255493164, 0.047426939010620117, 0.042778968811035156] f4: [0.04383397102355957, 0.039394140243530273, 0.039273977279663086, 0.045912027359008789, 0.039510011672973633]
source share