It was always my approach, and it worked fine, although I never did a lot of speed testing. It works especially well when you need to iterate over permutations / combinations of numbers, since you can create such strings using functions in the itertools package.
There are, of course, other methods that include less simple mathematical operations, but if the speed is absolutely low, I feel that the string method is Pythonic itself.
Here, for example, is a more mathematical approach, where a and b are indexed on the right (i.e., one place is 0, tenth place is 1, etc.):
def getSubdigits(n, a, b): n %= 10 ** a n //= 10 ** b return n
To do this, to work with the same indexing as string slicing, you first need to find the total number of digits, and the function will look like this:
def getSubdigits2(n, a, b): l = int(math.ceil(math.log10(n))) n %= 10 ** (l - a) n //= 10 ** (l - b) return n
And the equivalent of the string:
def subDigits3(n, a, b): return int(str(n)[a:n])
Here are the sync results:
subDigits : 0.293327726114subDigits2 : 0.850861833337subDigits3 : 0.990543234267
My contribution from this result is that the slicing method is great if you really don't care about speed, in which case you need to use the first method and think about indexes in a different direction.