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 indicates that all characters entered are numbers, otherwise, not all of them 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 headings
Str.isspace () All characters are whitespace characters, \ t, \ n, \ r
The above is mainly for the integer type of numbers, but for the floating point number is not applicable, then how to judge the floating point, has been entangled in this problem, why do we have to distinguish between integral type and floating point, since all are involved in the operation, all applicable floating point is not the same, after the result, the direct conversion to int is not the same Why do you have to tangle in the early to determine whether the integer or floating-point, with such ideas, the following is good to do, for example:
We can judge by the exception syntax as follows:
Try
{statements}
Exception: {Exception Objects}
{statements}
str = raw_input ("Please input the number:")
Try
f = Float (str)
Exception ValueError:
Print ("Input is not a number!") ")
==========================================================
There is also a method of purely judging whether it is a floating-point number, using a regular expression:
#引用re正则模块
Import re
Float_number = str (input ("Please input the number:"))
#调用正则
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. For this regular expression, explain:
^[-+]? [0-9]+\. [0-9]+$
^ denotes the beginning of this character, which begins with [-+], [-+] represents the character-or one of the +,
? represents 0 or 1, which means the symbol is optional.
Similarly [0-9] represents a number from 0 to 9, + represents 1 or more, which is the integer part.
\. Represents the decimal point, \ is the escape character because. is a special symbol (matches any single character except \ r \ n),
So you need to escape.
In the same vein as the decimal part, $ indicates that the string ends with this.
Just begin to learn the regular, there is the wrong place please correct me.
Determine if Python input is a number