How does python determine if the input is a number?
After receiving the raw_input method, determine whether the received string is a number
For example: str = raw_input("please input the number:")
if str.isdigit():
True means that all characters entered are numbers, otherwise, not all are numbers.str is a string
str.isalnum() All characters are numbers or letters
str.isalpha() All characters are letters
str.isdigit() All characters are numbers
str.islower() All characters are lowercase
str.isupper() All characters are uppercase
str.istitle() All words are capitalized, like titles
str.isspace() All characters are blank characters, \t, \n, \r
The above is mainly for integer numbers, but it is not applicable to floating point numbers.So how to judge floating point numbers? I have been struggling with this question.Why do I have to distinguish between integer and floating point numbers, since they are all involved in calculations Isn’t it the same for all floating-point numbers? After getting the result, it’s not the same to convert directly to int type.Why do you have to struggle to determine whether it is an integer or a floating-point number in the early stage? With this idea, just do the following Up, for example:
We can judge by the exception, the exception syntax is as follows: try:
{statements}
exception: {Exception Objects}
{statements}
str = raw_input("please input the number:")
try:
f = float(str)
exception ValueError:
print("The input is not a number!")
================================================== ========
There is also a purely method of judging whether it is a floating-point number, using regular expressions:
#Quote re regular module
import re
float_number = str(input("Please input the number:"))
#Call regular value = re.compile(r'^[-+]?[0-9]+\.[0-9]+$')
result = value.match(float_number)
if result:
print "Number is a float."
else:
print "Number is not a float."
2.About this regular expression, explain:
^[-+]?[0-9]+\.[0-9]+$
^ Means starting with this character, that is, starting with [-+], [-+] means one of the characters-or +,
? Means 0 or 1, which means that the symbol is optional.
Similarly, [0-9] represents a number from 0 to 9, and + represents one or more, which is the integer part.
\.means the decimal point, \ is an escape character because.Is a special symbol (matches any single character except \r\n),
So it needs to be escaped. The same is true for the fractional part, $ means that the string ends with this.
0 Comments