STR is string s as String
Str.isalnum () All characters are numbers or letters
Str.isalpha () All characters are letters
Str.isdigit () All characters are numbers
Str.isspace () All characters are whitespace characters, \ t, \ n, \ r
Check that the string is a numeric/floating-point method
Float section
>> float (' nan ') nan>> float (' nan ') nan>> float (' nan ') nan>> float (' inf ') inf>> float (' inf ') inf>> float ('-inf ') inf>> float ('-inf ') inf
The first type: the simplest
def is_number (str): try: # Because one exception to using float is ' nan ' if str== ' nan ': return False float (str) return True except ValueError: return False # Float Exception Example >>> float (' nan ') nan
Using complex ()
def is_number (s): try: complex (s) # for int, long, float and complex except ValueError: return false< C13/>return True
Synthesis 1
def is_number (s): try: float (s) # for int, long and float except ValueError: try: complex (s) # For complex except ValueError: return False return True
Synthesis 2-still not fully recognized
def is_number (n): is_number = True try: num = float (n) # check "nan" is_number = num = = num # or use ' m Ath.isnan (num) ' except valueerror: is_number = False return is_number >>> is_number (' Nan ') false>>> is_number (' nan ') False>>> is_number (' 123 ') true>>> is_number (' -123 ') true>>> is_number (' -1.12 ') True >>> is_number (' abc ') false>>> is_number (' inf ') True
The second type: can only be judged as integers
Using IsNumeric ()
# str must be Uniconde mode >>> str = u "345" >>> str.isnumeric () True
Http://www.tutorialspoint.com/python/string_isnumeric.htm
Http://docs.python.org/2/howto/unicode.html
Using IsDigit ()
Https://docs.python.org/2/library/stdtypes.html#str.isdigit
>>> str = "one" >>> print str.isdigit () true>>> str = "3.14" >>> print str.isdigit () false>>> str = "AAA" >>> print str.isdigit () False
Use INT ()
def is_int (str): try: int (str) return True except ValueError: return False
Third: Using the regular (safest method)
Import redef is_number (num): pattern = re.compile (R ' ^[-+]?[ -0-9]\d*\.\d*| [-+]?\.? [0-9]\d*$ ') result = Pattern.match (num) if result: return True else: return False >> : Is_number (' 1 ') True>>>: Is_number (' 111 ') True>>>: Is_number (' 11.1 ') true>>>: Is_ Number (' -11.1 ') True>>>: Is_number (' inf ') False>>>: Is_number ('-inf ') False
Original: Python determines whether a string is a letter or a number (floating point)
Python determines whether a string is a letter or a number (floating point)