How to get the number of digits. Casting the mold is a bit cumbersome but easy. [Addition] In the comment, I mentioned it because I was told how to do it smarter!
Convert a number to a string to get the length. If it is a negative number, the minus sign will be included in the number of digits, so convert it to an absolute value.
num = -12345
num = abs(num) #Convert to absolute value
num_str = str(num) #Convert to string
num_digits = len(num) #Get the length (number of digits) of the character string
print(num_digits) #Execution result 5
Or in one line
num = -12345
num_digits = len(str(abs(num))) #Batch conversion
print(num_digits) #Execution result 5
It is basically the same as the case of integers, but since it is the number of digits, the decimal point is excluded.
num = 0.123456
num = abs(num)
num_str = str(num).replace(".","") #Ignore the decimal point
num_digits = len(num)
print(num_digits) #Execution result 7
Count using isdigit () to determine if it is a number. Both integers and decimals can be written in this way.
def count_digit(value):
return sum(c.isdigit() for c in str(value))
print(count_digit(-12345)) #Execution result 5
print(count_digit(0.12345)) #Execution result 6
print(count_digit(-3.14)) #Execution result 3
Recommended Posts