I wanted to create a collection of all ASCII letters (both upper- and lowercase) and single digits in Python.
The first (IMO most Pythonic) way that I came up with uses the standard string concatenation operator:
import string
a = string.ascii_letters + string.digits
Then I wondered, would it be faster to use the usual methods to format strings?
Say, a = "%s%s" % (string.ascii_letters, string.digits)
or a = "{0}{1}".format(string.ascii_letters, string.digits)
?
Only timeit.timeit
can tell.
>>> timeit("a = string.ascii_letters + string.digits", setup="import string", number=10000000)
1.4662139415740967
>>> timeit("a = \"%s%s\" % (string.ascii_letters, string.digits)", setup="import string", number=10000000)
2.8996360301971436
>>> timeit("a = \"{0}{1}\".format(string.ascii_letters, string.digits)", setup="import string", number=10000000)
12.925632953643799
Interesting, innit. Now, a word of caution: these results are limited to this particular example. Results may vary (and probably do) if the “domain of the experiment” changes – that is, if you use different strings in terms of number, length, characters, etc.