0

How can I pick one of the digits from an Integer like: 97723 and choose (for example) the number 2 from that number and check if its an odd or an even number?

Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)

Thanks in advance

Pitipaty
  • 279
  • 7
  • 21

4 Answers4

3

2 is the 4th digit.

You can get the digits of a number using this construct.

digits = [int(_) for _ in str(97723)]

This expression will be true if the 4th digit is even.

digits[3] % 2 == 0
kmario23
  • 57,311
  • 13
  • 161
  • 150
Bill Bell
  • 21,021
  • 5
  • 43
  • 58
  • This won't generalize. I think the OP is looking for a method to pick an arbitrary digit out of a number. – kmario23 Oct 05 '16 at 21:04
  • My objective was to offer a simple answer to a simple question. What sort of generalisation would you like? – Bill Bell Oct 05 '16 at 23:04
1
# choose a digit (by index)

integer = 97723

digit_3 = str(integer)[3]

print(digit_3)

# check if even:

if int(digit_3) % 2 == 0:
    print(digit_3, "is even")


# get all odd numbers directly

odd_digits = [digit for digit in str(integer) if int(digit) % 2 == 1]

print(odd_digits)
Ben
  • 5,952
  • 4
  • 33
  • 44
0
even = lambda integer: int("".join([num for num in str(integer) if int(num) % 2 == 0]))

or

def even(integer):
    result = ""
    integer = str(integer)
    for num in integer:
        if int(num) % 2 == 0:
            result += num
    result = int(result)
    return(result)
Ledorub
  • 354
  • 3
  • 9
0

If you want to "parse" a number the easiest way to do this is to convert it to string. You can convert an int to string like this s = string(500). Then use string index to get character that you want. For example if you want first character (number) then use this string_name[0], for second character (number) use string_name[1] . To get length of your string (number) use len(string). And to check if number is odd or even mod it with 2.

# Converting int to string
int_to_sting = str(97723)

# Getting number of characters in your string (in this case number)
n_of_numbers = len(int_to_sting)

# Example usage of string index
print("First number in your number is: ",int_to_sting[0])
print("Second number in your number is: ",int_to_sting[1])

# We need to check for every number, and since the first number is int_to_sting[0] and len(int_to_sting) returns actual length of string we need to reduce it by 1
for i in range(n_of_numbers-1):
        if int_to_sting[i]%2==0:
              print(int_to_sting[i]," is even")
        else:
              print(int_to_sting[i]," is odd")
Tuc3k
  • 1,032
  • 9
  • 12