如何从Integer中选择一个数字,如:97723 并从该数字中选择(例如)数字2并检查它是奇数还是偶数?
另外,我可以直接打印整数中的奇数吗? (那是否有任何默认功能?)
提前致谢
答案 0 :(得分:3)
2是第4位数。
您可以使用此构造获取数字的数字。
digits = [int(_) for _ in str(97723)]
如果第四位数是偶数,则此表达式为true
。
digits[3] % 2 == 0
答案 1 :(得分: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)
答案 2 :(得分:0)
even = lambda integer: int("".join([num for num in str(integer) if int(num) % 2 == 0]))
或
def even(integer):
result = ""
integer = str(integer)
for num in integer:
if int(num) % 2 == 0:
result += num
result = int(result)
return(result)
答案 3 :(得分:0)
如果你想解析"一个数字最简单的方法是将其转换为字符串。您可以将int转换为此s = string(500)
之类的字符串。然后使用字符串索引来获取所需的字符。例如,如果您想要第一个字符(数字),则使用此string_name[0]
,第二个字符(数字)使用string_name[1]
。要获取字符串的长度(数字),请使用len(string)
。并检查数字是否为奇数或甚至用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")