How to extract indivudual odd numers from a number in python?

Viewed 57

I am currently working on a class assignment where I need to extract the odd numbers from the regular numbers and work with those numbers. How would I go about that?

For example... the user inputs 1327421. I want to extract the odd numbers from that number. 1, 3, 7, 1

Is there a way to do that?

2 Answers

If you're only looking for single-digit odd numbers like the example you supplied, you can do this by converting the input number to a list, then search through that list for odd numbers by checking if num%2 != 0. If you would like more help, update your post with an attempt at a solution.

Quick answer: in order to iterate over the digits of a number, you can turn it into a string, then iterate over it and convert the characters to digits.

number = 56189437
odd_digits = [int(char) for char in str(number) if int(char) % 2 == 1]
print(odd_digits)
# >> [5, 1, 9, 3, 7]

In order to do something more "mathematical" you could iterate over power of n in [0, N] and look at number // 10**n - (number // 10**(n+1)) * 10, which would be the digit at position n counting from the right.

Related