transhumanist.liberation wroteLike if we have an integer
a = 1234
b = a % 10 #extracts the final digit 4
what about If I wanna extract the 2nd to last digit 3? Similarly for 1 & 2
I am using Python 3
Your way
- What's a % 100?
- What's [(a % 100) - (a % 10)] / 10?
- What's [(a % 1000) - (a % 100)] / 100?
- What's [(a % 10**n) - (a % 10**(n-1))] / 10**(n-1)
This should get you where you want, but it's a convoluted way of doing it.
The better way
What others suggested, transform your number into a string, and access each element of the array by position. Remember to cast it back to a number before you do math on it.
The one-line way
DON'T DO THIS
This is bad coding style, but it's fun and it works. Here's how I sum the digits of the factorial of a number
n:
import math
def f(n):
return sum([int(d) for d in str(math.factorial(n))])
While it's bad style to write this code, it's important that you can read it and understand it. If something doesn't make sense, ask here.